passing data between sirikit intent handler and the app - ios

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.

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

Pass data to Call Directory Extension

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).

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.

Cannot access NSUserDefaults using app groups one to another

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

iOS 9 ShareData between AppGroup through NSUserDefaults

I'm trying to add TodayExtension to my existing app and I want that app and extension will share data through NSUserDefaults.
According to this tutorial http://www.glimsoft.com/06/28/ios-8-today-extension-tutorial/
I did like it say:
Create new target with Today extension
Add new App-Group in Extension and App
Add code to app
Add code to extension
App Code
func updateExtensionData() {
let key = "identityCode"
let valueForStore:Float = 2.0
let extensiontDefaults = NSUserDefaults(suiteName: "group.company.mineSharedDefaults")
extensiontDefaults?.setFloat(valueForStore, forKey: key)
let results = extensiontDefaults?.synchronize()
let checkCode = extensiontDefaults?.objectForKey(key)
print("code for save \(valueForStore) synchronize result \(results) readed code \(checkCode!)")
}
Extension code
private func updateData() {
let key = "identityCode"
let extensionDefaults = NSUserDefaults(suiteName: "group.company.mineSharedDefaults")
let checkCode = extensionDefaults?.floatForKey(key)
print("synchronize result \(resut) readed code \(checkCode!)")
}
Issue
My issue is that extension always read 0 instead of 2. Clearly I'm missing something. There is some major difference between iOS8 and 9 in case of AppGroup and NSUserDefaults? I know that there is but between app an watchOS2.
For being more clear this is keys from App and Extension NSUserDefaults
App Keys
AppleKeyboards
AppleKeyboardsExpanded
AddingEmojiKeybordHandled
AppleLanguages
ApplePasscodeKeyboards
PreferredLanguages
AppleLocale
NSInterfaceStyle
MSVLoggingMasterSwitchEnabledKey
NSLanguages
AppleITunesStoreItemKinds
identityCode
AppleLanguagesDidMigrate
PKEnableStockholmSettings
Extension Keys
AppleKeyboards
AppleKeyboardsExpanded
AddingEmojiKeybordHandled
AppleLanguages
ApplePasscodeKeyboards
PreferredLanguages
AppleLocale
NSInterfaceStyle
MSVLoggingMasterSwitchEnabledKey
NSLanguages
AppleITunesStoreItemKinds
AppleLanguagesDidMigrate
PKEnableStockholmSettings
It's clear that key identityCode is not appearing in extension at all.
Ok I'm not sure what helps but I've done two thing:
rename current AppGroup identifier and create new one with name group.my.entire.bundle.id.of.my.app.sharedData instead of group.appname.sharedData
remove and create new AppGroup identifier
I can use "identityCode" as key.
CThere could be several things!
first; did you allow keychain sharing under "Capabilities" for both your container app and the extension, and did you set the Keychain groups to the same group?
I recommend using this: https://github.com/kefbytes/KeychainWrapper
download it, it's very simple, just add the swiftfile to your project
allow keychain sharing under cabailities,
set your serviceName and accesgroup like this
KeychainWrapper.serviceName = "give it a name in here"
(servicename is neccessary for it to work)
KeychainWrapper.accessGroup = "write your accessgroup name here"
(accesgroup is optional, since you are setting it under Capabilities)
save a value to a key like this
KeychainWrapper.setString("2", forKey: "identityCode"
and retrieve with
KeychainWrapper.stringForKey("identityCode")

Resources