NSUserDefaultsApp群组WatchKit swift

时间:2015-12-16 16:49:45

标签: swift nsuserdefaults watchkit

我尝试使用NSUserdefaults编写一个小型测试应用程序,以便在iPhone和Watch之间进行通信。但是在尝试了很多解决方案后它仍然无效。所以我在这里发布我的代码以寻求帮助。谢谢!

iPhone方面: 导入UIKit

类ViewController:UIViewController {

@IBOutlet var addLabel: UILabel!

var n : Int = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func addBtn(sender: AnyObject) {        
    n++
    addLabel.text = "\(n)"     
}

@IBAction func sendBtn(sender: AnyObject) {

    let mySharedDefaults = NSUserDefaults(suiteName: "group.com.sunyi.sharingdatasunyi")

    mySharedDefaults?.setInteger(n, forKey: "savedUserInput")

    mySharedDefaults?.synchronize()
}

}

手表方面: 导入WatchKit 进口基金会

class InterfaceController:WKInterfaceController {

@IBOutlet var myWatchLabel: WKInterfaceLabel!

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)      
    // Configure interface objects here.
}

override func willActivate() {
    // This method is called when watch view controller is about to be visible to user
    super.willActivate()
}

override func didDeactivate() {
    // This method is called when watch view controller is no longer visible
    super.didDeactivate()
}

@IBAction func showBtn() {

    let mySharedDefaults = NSUserDefaults(suiteName: "group.com.sunyi.sharingdatasunyi")

    mySharedDefaults?.synchronize()

    var a : Int = -1

    a = mySharedDefaults!.integerForKey("savedUserInput")

    self.myWatchLabel.setText("\(a)")

}

}

我已经构建了应用程序组,ID是group.com.sunyi.sharingdatasunyi。项目名称是sharingdatasunyi。 Bundle ID是com.sunyi.sharingdatasunyi。最后结果是:无论我在iPhone端输入什么,在按下ShowButton后,标签总是显示0(不是-1,不是我的输入数字)。那么,我该怎么办?

非常感谢你!

1 个答案:

答案 0 :(得分:0)

您使用的是watchOS 1还是2?在watchOS 2上,即使他们使用共享组,您也无法使用NSUserDefaults在手表和iPhone之间进行通信。您应该考虑使用WatchConnectivity和sendMessage在两个设备之间实时通信。