我有一个用Swift编写的简单iOS应用程序,它使用CloudKit将字符串保存到云中。用户可以随时更新字符串(覆盖原始字符串)。这在我的代码中正常工作。如果用户在其他设备上更改字符串(例如,他们对iPad上的字符串进行更改,我希望他们的iPhone自动更新),我希望应用自动更新。我试图找到一个基本的CloudKit订阅教程,但它们都处理更高级的实现。我如何实现简单的CloudKit订阅?我的代码如下:实现基本的CloudKit订阅
import UIKit
import CloudKit
class ViewController: UIViewController {
// This the text field where the user inputs their string to save to the cloud
@IBOutlet weak var userInput1: UITextField!
// Save button
// When the user taps save, their string is saved to the cloud
@IBAction func saveButton(sender: AnyObject) {
let container = CKContainer.defaultContainer()
let privateDatabase = container.privateCloudDatabase
let myRecordName = "1001"
let recordID = CKRecordID(recordName: myRecordName)
privateDatabase.fetchRecordWithID(recordID, completionHandler: { (record, error) in
if error != nil {
} else {
record!.setObject(self.userInput1.text, forKey: "userInput1")
privateDatabase.saveRecord(record!, completionHandler: { (savedRecord, saveError) in
if saveError != nil {
print("Error saving record.")
} else {
print("Successfully updated record!")
}
})
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Auto populates app with cloud string
let container = CKContainer.defaultContainer()
let privateDatabase = container.privateCloudDatabase
let myRecordName = "1001"
let recordID = CKRecordID(recordName: myRecordName)
privateDatabase.fetchRecordWithID(recordID, completionHandler: { (record, error) in
if error != nil {
// Nothing saved to cloud yet
print(error)
} else {
// Display record
dispatch_async(dispatch_get_main_queue()) {
self.userInput1.text = (record!["userInput1"]! as! String)
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
谢谢你的信息...我现在有点工作了.. 。我有我的iPhone插入,我正在iPhone上的Xcode测试应用程序。当我通过CloudKit Dashboard进行记录更新时,我收到一条通知,表示记录“XYZ”已更新。只需确认,该通知实际上并不包含更新的记录?它只包含更新的记录的ID? – user1822824