我试图在用户在我的应用中创建新事件时发送通知。我可以成功设置通知,因为我可以在我的云套件仪表板中看到它,但是当有人创建事件时,没有任何反应......
事情是:在ViewController1中,用户选择事件的名称和参与者,在ViewController2中,他继续选择其他一些东西。我想说的是我不需要在我的应用程序中上传任何视觉细节(当通知到达时),我只想在通知出现时,用户直接进入ViewController2。这是我的代码:
App代表:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
let cloudKitNotification = CKNotification(fromRemoteNotificationDictionary: userInfo as! [String : NSObject])
if cloudKitNotification.notificationType == CKNotificationType.Query {
NSNotificationCenter.defaultCenter().postNotificationName("notinoti", object: nil)
}
}
ViewController1:
func setupCloudKitSubscription() {
let userDefaults = NSUserDefaults.standardUserDefaults()
if userDefaults.boolForKey("subscribed") == false {
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let subscription = CKSubscription(recordType: "Event", predicate: predicate, options: CKSubscriptionOptions.FiresOnRecordCreation)
let notificationInfo = CKNotificationInfo()
notificationInfo.alertLocalizationKey = "New event"
notificationInfo.shouldBadge = true
notificationInfo.desiredKeys = ["name"]
subscription.notificationInfo = notificationInfo
let publicData = CKContainer.defaultContainer().publicCloudDatabase
publicData.saveSubscription(subscription, completionHandler: { (subscription, error) in
if error != nil {
print(error?.localizedDescription)
} else {
userDefaults.setBool(true, forKey: "subscribed")
userDefaults.synchronize()
}
})
}
}
ViewController2:
var currentRecord: CKRecord?
override func viewDidLoad() {
super.viewDidLoad()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
NSNotificationCenter.defaultCenter().addObserver(self , selector: Selector("fetchRecord"), name: "notinoti", object: nil)
})
}
func fetchRecord(recordID: CKRecordID) -> Void {
let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase
publicDatabase.fetchRecordWithID(recordID, completionHandler: ({record, error in
if let err = error {
dispatch_async(dispatch_get_main_queue()) {
print(err.localizedDescription)
}
} else {
dispatch_async(dispatch_get_main_queue()) {
self.currentRecord = record
//Now do something with the data
}
}
}))
}
答案 0 :(得分:0)
佩德罗,
不知道它是否重要,但我的工作"订阅行读取。我的代码中有一个subscriptionID?
let subID = String(NSUUID().UUIDString)
let predicateY = NSPredicate(value: true)
let subscription = CKSubscription(recordType: "Blah", predicate: predicateY, subscriptionID: subID, options: [.FiresOnRecordUpdate, .FiresOnRecordDeletion])
我得到了一个模糊的回忆,它在用它愚弄了一段时间之后没有工作,此时我重置了云套件仪表板上的数据库并重新订阅了,它又恢复了工作。