0

I have two apps: App1 and App2.

In App1 I saved a key tokenvalue to NSUserDefaults.

I need to get the same tokenvalue in App2 as I got in App1. Is there any possiblity to get that value other than by using keychains?

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
S P Balu Kommuri
  • 890
  • 10
  • 28
  • Check below link : http://stackoverflow.com/questions/24015506/communicating-and-persisting-data-between-apps-with-app-groups?answertab=votes#tab-top – KKRocks Oct 18 '16 at 11:36
  • yes, you can, that is not an issue. – holex Oct 18 '16 at 11:44

2 Answers2

3

You have to use App Groups. This will let both apps save to a shared NSUserDefaults and File folder.

In Xcode, click on your project folder Project Name -> DesiredTarget -> Capabilities -> App Group, turn it on and create an associated app group.

Do this procedure for both App1 and App2.

from the docs: https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html

// Create and share access to an NSUserDefaults object
NSUserDefaults *mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName: @"com.example.domain.MyShareExtension"];

// Use the shared user defaults object to update the user's account
[mySharedDefaults setObject:theAccountName forKey:@"lastAccountName"];
Danny Yassine
  • 661
  • 7
  • 9
3

To store data:

var userDefaults = NSUserDefaults(suiteName: "group.com.company.App")
userDefaults!.setObject("token123", forKey: "tokenvalue")
userDefaults!.synchronize()

To retrieve data:

var userDefaults = NSUserDefaults(suiteName: "group.com.company.App")
if let tokenId = userDefaults?.objectForKey("tokenvalue") as? String {
  print("User Id: \(tokenId)")
}
Nilesh Jha
  • 1,626
  • 19
  • 35