Cannot access NSUserDefaults using app groups one to another - ios

I'm working on an app and a widget that the widget needs to get data from app. I've used the following codes to read and write on NSUserDefaults. And also I used $(PRODUCT_BUNDLE_IDENTIFIER).widget for widget and $(PRODUCT_BUNDLE_IDENTIFIER) referring to this post. But widget cannot get the data from app or NSUserDefaults. How can I make it work?
func addTask(name: String?) {
let key = "keyString"
tasks.append(name!)
let defaults = NSUserDefaults(suiteName: "group.Mins")
defaults?.setObject(tasks, forKey: key)
defaults?.synchronize()
}
///////
let defaults = NSUserDefaults(suiteName: "group.Mins")
let key = "keyString"
if let testArray : AnyObject = defaults?.objectForKey(key) {
let readArray : [String] = testArray as! [String]
timeTable = readArray
timeTable = timeTable.sort(<)
print("GOT IT")
print("timetable: \(timeTable)")
}

To read and save from the same set of NSUserDefaults you need to the the following:
In your main app, select your project in the project navigator.
Select your main app target and choose the capabilities tab.
Switch on App Groups (this will communicate with the developer portal, as it is generating a set of entitlements, and relevant App Id and so forth).
Create a new container. According to the help, it must start with “group.”, so give it a name like “group.myapp.test”.
Select your Today Extension target and repeat this process of switching on app groups. Don’t create a new one, rather select this newly created group to signify that the Today Extension is a member of the group.
Write to your NSUserDefaults:
// In this example I´m setting FirstLaunch value to true
NSUserDefaults(suiteName: "group.myapp.test")!.setBool(true, forKey: "FirstLaunch")
Read from NSUserDefaults:
// Getting the value from FirstLaunch
let firstLaunch = NSUserDefaults(suiteName: "group.myapp.test")!.boolForKey("FirstLaunch")
if !firstLaunch {
...
}
Swift 4.x:
Write:
UserDefaults(suiteName: "group.myapp.test")!.set(true, forKey: "FirstLaunch")
Read:
UserDefaults(suiteName: "group.myapp.test")!.bool(forKey: "FirstLaunch")

Related

Transfer data from project to widget in swift

At my project i need to send user id's to widget in iOS. But for do that, my user needs to open application once. Without opening, information stays only 1 day, after that it vanishes and widget stops showing information and await for opening application.
For do that i used appGroup.
What is the correct way to use transfer data from my project to widget?
Swift 5
Follow these steps to pass data from the host app to extensions.
Select project target > Capabilities > add new app group (if you have enabled permissions for your developer account otherwise enable that first)
Select the extension target and repeat the same.
if let userDefaults = UserDefaults(suiteName: "group.com.yourAppgroup") {
createEventDic.removeAll()
let eventDic = NSMutableDictionary()
eventDic.setValue("YourString", forKey: "timeFontName")
createEventDic.append(eventDic)
let resultDic = try? NSKeyedArchiver.archivedData(withRootObject: createEventDic, requiringSecureCoding: false)
userDefaults.set(resultDic, forKey: "setWidget")
userDefaults.synchronize()
} else {
}
Now go to your app extension and do these steps to get the passed data.
if let userDefaults = UserDefaults(suiteName: "group.com.yourAppGroup") {
guard let testcreateEvent = userDefaults.object(forKey: "testcreateEvent") as? NSData else {
print("Data not found in UserDefaults")
return
}
do {
guard let eventsDicArray = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(testcreateEvent as Data) as? [NSMutableDictionary] else {
fatalError("loadWidgetDataArray - Can't get Array")
}
for eventDic in eventsDicArray {
let timeFontName = eventDic.object(forKey: "timeFontName") as? String ?? ""
}
} catch {
fatalError("loadWidgetDataArray - Can't encode data: \(error)")
}
}
Hopefully, it will help. Cheers!
For do that i used appGroup.
What is the correct way to use transfer data from my project to
widget?
What you did so far (App Grouping) is one of the steps that you should follow. Next, as mentioned in App Extension Programming Guide - Sharing Data with Your Containing App:
After you enable app groups, an app extension and its containing app
can both use the NSUserDefaults API to share access to user
preferences. To enable this sharing, use the initWithSuiteName: method
to instantiate a new NSUserDefaults object, passing in the identifier
of the shared group.
So, what you have to do so far is to let the data to be transferred by the UserDefautls. For instance:
if let userDefaults = UserDefaults(suiteName: "group.com.example.myapp") {
userDefaults.set(true, forKey: "myFlag")
}
thus you could pass it to the widget:
if let userDefaults = UserDefaults(suiteName: "group.com.example.myapp") {
let myFlag = userDefaults.bool(forKey: "myFlag")
}
And you follow the same approach for passing the data vise-versa (from the widget to the project).
In Xamarin Forms, we need to use DI to pass the data to the ios project then we can put it into NSUserDefaults
Info: Grouping application is mandatory
Xamarin iOS project - Putting Data into NSUserDefaults
var plist = new NSUserDefaults("group.com.test.poc", NSUserDefaultsType.SuiteName);
plist.SetBool(true, "isEnabled");
plist.Synchronize();
Today Extension - Getting data from NSUserDefaults
var plist = new NSUserDefaults("group.com.test.poc", NSUserDefaultsType.SuiteName);
var result = plist.BoolForKey("isEnabled");
Console.WriteLine($"The result of NSUserdefaults: logesh {result}");

Saving data (numbers) in an iOS app?

I'm learning application development working on a quiz game. I'd like to add statistics to the game. For example, the average score since the app has been downloaded. How can I store the scores on the device in order to reuse them after the app has been closed?
You should take a look at UserDefault. It's basically a dictionary that persists until the user uninstalls your app. I like to write a wrapper around it to get strong typing and ease of reference:
struct Preferences {
static func registerDefaults() {
UserDefaults.standard.register(defaults: [kAverageScore: 0])
}
// Define your key as a constant so you don't have to repeat a string literal everywhere
private static let kAverageScore = "averageScore"
static var averageScore: Double {
get { return UserDefaults.standard.double(forKey: kAverageScore) }
set { UserDefaults.standard.set(newValue, forKey: kAverageScore) }
}
}
Here's how to use it: before you call it for the first time in your app, you must register the defaults. These are the values that your app ships with. On iOS, it only really matters for the very first time the user launches your app. On OS X, do this every time your app starts because the user can delete the app's preferences from ~/Library/Application Support.
// You usually do this in viewDidLoad
Preferences.registerDefaults()
From then on, getting and setting the property is easy:
let averageScore = Preferences.averageScore
Preferences.averageScore = 5.5
You should take a look at UserDefaults
Example
let defaults = UserDefaults.standard
defaults.set(25, forKey: "Age")
defaults.set(true, forKey: "UseTouchID")
defaults.set(Double.pi, forKey: "Pi")
To read values back
let age = defaults.integer(forKey: "Age")
let useTouchID = defaults.bool(forKey: "UseTouchID")
let pi = defaults.double(forKey: "Pi")
UserDefaults

Shared UserDefaults between app and extension not working correctly

So I've been looking around and following all the steps to setup shared UserDefaults correctly but I should be missing something.
I have App Groups capability activated on both my app and my extension. Both use the same suite name ("group.TestSharedPreferences") and I write this way:
struct Preferences {
static let shared = UserDefaults(suiteName: "group.TestSharedPreferences")!
}
On viewDidLoad:
Preferences.shared.set(1, forKey: "INT")
And to read:
Preferences.shared.integer(forKey: "INT") // Returns 1 in Container App
Preferences.shared.integer(forKey: "INT") // Returns 0 in Today Extension
Even using synchronize() just after setting "INT", the value retrieved in the extension is not the one saved in the container App. Any ideas on what might I be missing? Thank you!
I would recommend to dig down step by step here.
First, make sure that both the main app and the widget extension have app group capability enabled and use the same and activated (the checkmark must be set) app group name:
Main App:
Today Widget Extension:
Then make a simple test with direct set/get access. In your main app's AppDelegate.didFinishLaunchingWithOptions method (change the app group name and the keys to your needs):
if let userDefaults = UserDefaults(suiteName: "group.de.zisoft.GPS-Track") {
userDefaults.set("test 1" as AnyObject, forKey: "key1")
userDefaults.set("test 2" as AnyObject, forKey: "key2")
userDefaults.synchronize()
}
In your Today Widget Extension's ViewController:
if let userDefaults = UserDefaults(suiteName: "group.de.zisoft.GPS-Track") {
let value1 = userDefaults.string(forKey: "key1")
let value2 = userDefaults.string(forKey: "key2")
...
}
If this works, the problem must be related in your Preferences singleton.

Why doesn't NSUserDefaults work between my app & share extension?

I have an iOS app with a share extension. I am trying to share data between them using NSUserDefaults and App Groups but, while I can write into the NSUD object, read it, and synchronize() without error, reading in the extension always results in nil.
I have an app group, the literal string "group.net.foo.bar" for which both the app & extension have configured under Capabilities -> App Groups. This string is in a constants struct in my app:
struct Forum {
static let APP_GROUP = "group.net.foo.bar"
static let AUTH_KEY = "AUTH_KEY"
}
In the main app I create a UserDefaults object and write to it:
fileprivate lazy var userDefaults: UserDefaults = {
let defaults = UserDefaults()
defaults.addSuite(named: Forum.APP_GROUP)
return defaults
}()
// later
userDefaults.set(apiKey, forKey: Forum.AUTH_KEY)
userDefaults.synchronize()
Creating a new NSUD object after that synchronize() and retrieving the AUTH_KEY works. In the extension, I create an NSUD and try to retrieve the value, to no avail:
private lazy var userDefaults: UserDefaults = {
let defaults = UserDefaults()
defaults.addSuite(named: Forum.APP_GROUP)
return defaults
}()
// later
private func getApiKey() -> String? {
return userDefaults.string(forKey: Forum.AUTH_KEY)
}
// returns nil
In all of my reading of the Apple docs and depressingly-similar questions here on Stack Overflow I can't divine what I've done incorrectly.
Xcode Version 8.0 (8A218a), also tested with Xcode 8.1 Beta 2. Same behavior on simulator andy my iPhone 6s running iOS 10.
Not sure if defaults.addSuite(named: ...) does the same as UserDefaults(suiteName: ...). In my app I use appGroups this way and it works as expected:
// write
if let userDefaults = UserDefaults(suiteName: appGroupName) {
userDefaults.set("---" as AnyObject, forKey: "distance")
userDefaults.set("---" as AnyObject, forKey: "altitude")
...
userDefaults.synchronize()
}
// read
if let userDefaults = UserDefaults(suiteName: appGroupName) {
self.distanceLabel.text = userDefaults.string(forKey: "distance")
self.altitudeLabel.text = userDefaults.string(forKey: "altitude")
}
if you suffer this problem when you try to save data to extension APP by using userDefault,maybe you had written this code : [[NSUserDefaults standardUserDefaults] initWithSuiteName:#"group.xxx.com"];,this code reset default userDefault. Actually,the correct code is : [[NSUserDefaults alloc] initWithSuiteName:#"group.xxx.com"]; enter link description here

Sharing data between an iOS 8 share extension and main app

Recently, I've been making a simple iOS 8 share extension to understand how the system works. As Apple states in its App Extension Programming Guide:
By default, your containing app and its extensions have no direct access to each other’s containers.
Which means the extension and the containing app do not share data. But in the same page Apple brings a solution:
If you want your containing app and its extensions to be able to share data, use Xcode or the Developer portal to enable app groups for the app and its extensions. Next, register the app group in the portal and specify the app group to use in the containing app.
Then it becomes possible to use NSUserDefaults to share data between the containing app and the extension. This is exactly what I would like to do. But for some reason, it does not work.
In the same page, Apple suggests the standard defaults:
var defaults = NSUserDefaults.standardUserDefaults()
In a WWDC presentation (217), they suggest a common package:
var defaults = NSUserDefaults(suiteName: kDefaultsPackage)
Also, I enabled App Groups for both the containing app target and the extension target, with the same App Group name:
But all this setup is for nothing. I cannot retrieve the data I stored in the containing app, from the extension. It is like two targets are using completely different NSUserDefaults storages.
So,
Is there a solution for this method?
How can I share simple data between the containing app and the share extension? The data is just user credentials for an API.
You should use NSUserDefaults like this:
Save data:
objc
NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:#"group.yougroup"];
[shared setObject:object forKey:#"yourkey"];
[shared synchronize];
swift
let defaults = UserDefaults(suiteName: "group.yourgroup")
defaults?.set(5.9, forKey: "yourKey")
Read data:
objc
NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:#"group.yougroup"];
id value = [shared valueForKey:#"yourkey"];
NSLog(#"%#",value);
swift
let defaults = UserDefaults(suiteName: "group.yourgroup")
let x = defaults?.double(forKey: "yourKey")
print(x)
This will work fine!
Here is how I did it:
Open your main app target > Capabilities > App Groups set to on
Add a new app group and make sure it is ticked (e.g. group.com.seligmanventures.LightAlarmFree)
Open your watch target (the one with Capabilities tab) > App Groups set to on
Add a new app group and make sure it is ticked (e.g. group.com.seligmanventures.LightAlarmFree - but must be the same name as group above)
Save data to the group as follows:
var defaults = NSUserDefaults(suiteName: "group.com.seligmanventures.LightAlarmFree")
defaults?.setObject("It worked!", forKey: "alarmTime")
defaults?.synchronize()
Retrieve data from the group as follows:
var defaults = NSUserDefaults(suiteName: "group.com.seligmanventures.LightAlarmFree")
defaults?.synchronize()
// Check for null value before setting
if let restoredValue = defaults!.stringForKey("alarmTime") {
myLabel.setText(restoredValue)
}
else {
myLabel.setText("Cannot find value")
}
If you have
group.yourappgroup
use
var defaults = NSUserDefaults(suiteName: "yourappgroup")
This works for me
So apparently it works, only when the group name is used as the suite name for NSUserDefaults.
The documentation says NSUserDefaults.standartUserDefaults() should also work but it does not, and this is probably a bug.
In my scenario I'm sharing data between the parent iOS app and WatchKit. I'm using Xcode 6.3.1, iOS Deployment Target 8.3
var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")
In your viewDidLoad make sure you synchronize:
override func viewDidLoad() {
super.viewDidLoad()
defaults?.synchronize()
}
Example of a button sending text but of course you can pass whatever:
#IBAction func btnSend(sender: UIButton) {
var aNumber : Int = 0;
aNumber = aNumber + 1
//Pass anything with this line
defaults?.setObject("\(aNumber)", forKey: "userKey")
defaults?.synchronize()
}
Then on the other side make sure app group matches:
var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")
Then synchronize and cal: (In this case "lblNumber" is an IBOutlet label)
defaults?.synchronize()
var tempVar = defaults!.stringForKey("userKey")!;
lblNumber.setText(tempVar);
Then if you wanted to set something on this side and sync it back then just do the same thing and synchronize and just make sure the stringForKey that you call on the other side is the same:
defaults?.setObject("sending sample text", forKey: "sampleKey")
defaults?.synchronize()
Hope this makes sense
I translated in swift foogry's answer and it works!!
Save data:
let shared = NSUserDefaults(suiteName: "nameOfCreatedGroup")
shared("Saved String 1", forKey: "Key1")
shared("Saved String 2", forKey: "Key2")
Read data:
let shared = NSUserDefaults(suiteName: "nameOfCreatedGroup")!
valueToRead1 = shared("Key1") as? String
valueToRead2 = shared("Key2") as? String
println(valueToRead1) // Saved String 1
println(valueToRead2) // Saved String 2
You may share data by Following below steps:
1) Select your project -> Select Capabilities tab -> Enable App Groups -> Click on '+' -> paste your bundle Id after 'group.'
2) Select your Extension -> Select Capabilities tab -> Enable App Groups -> Click on '+' -> paste your bundle Id after 'group.'
3) Place below code in your main app for which data you want to share:
NSUserDefaults * appGroupData = [[NSUserDefaults alloc]initWithSuiteName:#"group.com.appname"];
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:[self allData]]; // Get my array which I need to share
[appGroupData setObject:data forKey:#"Data"];
[appGroupData synchronize];
4) You may get object in extension:
NSUserDefaults * appGroupData = [[NSUserDefaults alloc] initWithSuiteName:#"group.com.appname"];
NSData * data = [appGroupData dataForKey:#"Data"];
NSArray * arrReceivedData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
You should use NSUserDefaults like this following and make sure
you must have enabled app group in your provisional profile and app group must configure as a green symbol and it should add to your provisional profile & BundleID.
NSUserDefaults *sharedUserDefault = [[NSUserDefaults alloc] initWithSuiteName:#"group.yougroup"];
[sharedUserDefault setObject:object forKey:#"yourkey"];
[sharedUserDefault synchronize];
NSUserDefaults *sharedUserDefault = [[NSUserDefaults alloc] initWithSuiteName:#"group.yougroup"];
sharedUserDefault value = [sharedUserDefault valueForKey:#"yourkey"];

Resources