S P Balu Kommuri
S P Balu Kommuri

Reputation: 890

Can we access App1's NSUserDefaults from App2?

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?

Upvotes: 0

Views: 88

Answers (2)

Nilesh Jha
Nilesh Jha

Reputation: 1636

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)")
}

Upvotes: 3

Danny Yassine
Danny Yassine

Reputation: 681

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"];

Upvotes: 3

Related Questions