1

I am trying to share data between my iOS and WatchKit extension using a common module contained in an embedded framework. The common module class has shared data held in an NSUserDefault with an App Group.

However what I write to the App Group share in the iOS app is not seen when reading from the WatchKit extension.

I have App Groups enabled with the same group ID in both the targets. The iOS reads and writes without error and if the Watch writes data it also reads it back without error -- but neither see the writes made by the other.

Any thoughts how to resolve greatly appreciated.

public class ShareManager() {
    private let sharedKey = “kungFuShare"

    public var kungfuFighters:Array<KungFu> = [];

    public init() {
        readFromShare()
    }

    public func readFromShare() {
        let myData = NSUserDefaults(suiteName: "group.com.27feathers.kungfu"
        if let rawData: NSData = myData?.objectForKey(sharedKey) as? NSData
        {                     
            var myData: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(rawData);
            self.kungfuFighters = myData as? [KungFu] ?? []
        }
    }

    public func writeToShare() {
        let myData = NSUserDefaults(suiteName: "group.com.27feathers.kungfu")
        let saveData = NSKeyedArchiver.archivedDataWithRootObject(self.kungfuFighters)
        myData?.setObject(saveData, forKey: sharedKey)
        myData?.synchronize() // same behavior with or without this
    }
}

public class KungFu: NSObject, NSCoding {
    public var fighterName:String

    public init(fighterName:String) {
        self.fighterName = fighterName
    }

    required public init(coder: NSCoder) {
        self.fighterName = coder.decodeObjectForKey("fighterName")! as String
        super.init()
    }

    public func encodeWithCoder(coder: NSCoder) {
       coder.encodeObject(self.fighterName, forKey: "fighterName")
    }
}
billd
  • 95
  • 6

1 Answers1

0

After simplifying to the most basic level of just saving a Bool to NSUserDefaults in the iOS app and then trying to read in the Watch, I found the read still failed.

This prompted me to register a new App Group in the Developer Center.

I then changed to the new App Group for the iOS and Watch targets. Once using the new App Group everything works! I am now able to write in iPhone app and read in Watch.

I have no idea why the first App Group did not work since I followed the exact same steps when creating the second one. Perhaps there is something buggy with this beta 6.2 version of Xcode

billd
  • 95
  • 6
  • I found adding an App group the first time incredibly cumbersome and undocumented. You should submit a bug report, I'd be happy to duplicate it – phillfarrugia Feb 08 '15 at 10:59