Share datas between two apps with iOS 8 App Groups (using NSUserDefaults)

走远了吗. 提交于 2019-11-26 23:08:44

问题


I wonder if we can share datas between apps with the new iOS 8 feature : App groups (using NSUserDefaults) - Or if App Groups only share datas between the main app and its extension?

I actually enabled the App Groups feature on both of the apps that should share datas between them (they belong the same company). They also have the same App Groups thing (like group.com.company.myApp).

Here's the code on the first one (in Swift)

    NSUserDefaults.standardUserDefaults().setBool(true, forKey:"Bool")
    NSUserDefaults.standardUserDefaults().synchronize()

And here's the code on the second one (in Objective-C)

    NSUserDefaults *datas = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.company.myApp"];
    NSLog(@"%@", [datas boolForKey:@"Bool"]);

Sadly, the Bool always returns nil.

If anyone has a solution :)

Thanks


回答1:


Check out this thread on the Apple Developer Forums: https://devforums.apple.com/message/977151#977151

I believe that both instances need to use the group ID (initializing with initWithSuiteName:) or else they are reading/writing to different user defaults sets.

So your Swift code would change to:

var userDefaults = NSUserDefaults(suiteName: "group.com.company.myApp")
userDefaults.setBool(true, forKey: "Bool")
userDefaults.synchronize()



回答2:


App Groups no longer work in WatchOS2. You must use the watch connectivity Framework.

in your iOS App:

import UIKit
import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    if (WCSession.isSupported()) {
        let session = WCSession.defaultSession()
        session.delegate = self
        session.activateSession()
    }

    do {
        let applicationDict = ["key" : "value"]
        try WCSession.defaultSession().updateApplicationContext(applicationDict)
    } catch {
        // Handle errors here
    }
}

}

In your Watch OS2 App:

import WatchKit
import WatchConnectivity
import Foundation

class InterfaceController: WKInterfaceController, WCSessionDelegate {

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
    print(applicationContext)
}


来源:https://stackoverflow.com/questions/24387871/share-datas-between-two-apps-with-ios-8-app-groups-using-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!