I cannot pass data call directory extension from main app
I've created one App group and turned it on in App capabilities for both targets (main app and extension)
I pass data with NSUser
-Create Data in main app
var userDefaults = UserDefaults(suiteName: "group.test.callapp")
userDefaults?.set("mynumber", forKey: "mykey")
-Retrieve Data in extension
var baseDescription = "test"
let newUserDefaults = UserDefaults(suiteName: "group.test.callapp")
if let testUserId = newUserDefaults?.object(forKey: "mykey") as? String
{
baseDescription = testUserId
}
When i do it in only main app - everything is ok, but when i do it in extension (i do it in 'addIdentificationPhoneNumbers' function) - it doesn't work, baseDescripton doesn't change
Your solutions shoud work, the only problem I can see is that you don't have App Groups enabled (with your "group.test.callapp" group) both for your application and the extension. Check Target->Capabilities if this is enabled for both. Another caveat is to pass the phone number in the international format (with country code).
ios does not let the containing app and the contained extensions to share a common container, so UserDefaults is the proposed solution.
I have tried using UserDefaults with sirikit intent handler assuming the handler behaves as an extension as follows :
inside IntentHandler.swift
let shared = UserDefaults(suiteName:XXXXXXXX.group...)
shared?.set("saved value 1", forKey: "key1")
shared?.set("saved value 2", forKey: "key2")
shared?.set("saved value 3", forKey: "key3")
inside ViewController.swift in viewDidLoad
let shared = UserDefaults(suiteName:XXXXXXXX.group...)
if let temp1 = shared?.string(forKey:"key1")
{
contentLabel.text = temp1
}
if let value = shared?.string(forKey: "key2")
{
valueLabel.text = value
}
if let key = shared?.string(forKey: "key3")
{
keyLabel.text = key
}
i can see the strings corresponding to key1 and key2 on my ipad screen but not for key3, peppering the code with synchronizes does not help.
here are my questions :
1) are sirikit handlers different from other extensions? if yes how to pass data to my app? if not am i using UserDefaults incorrectly?
2) is there a better way to handle IPC between the app and its extensions where i just need to pass simple string messages between them.
using swift 3.0 and xcode 8.2.1
Check that you have the App Group enabled for all targets you want to access the group from. Check in project -> your target -> capabilities under "App Groups".
There's something called MMWomhole. It will definitely do the work.
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.
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")
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"];