【问题标题】:SWIFT: I don't get notifications from my CloudKit app?SWIFT:我的 CloudKit 应用程序没有收到通知?
【发布时间】:2016-05-22 01:27:07
【问题描述】:

这是我的代码:

    @IBAction func sendSweet(sender: AnyObject) {

    //delegate method

    let newSweet = CKRecord(recordType: "Extra1")
    newSweet["content"] = textField.text

    let publicData = CKContainer.defaultContainer().publicCloudDatabase
    publicData.saveRecord(newSweet, completionHandler: { (record:CKRecord?, error:NSError?) -> Void in
        if error == nil {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tableView.beginUpdates()
                self.sweets.insert(newSweet, atIndex: 0)
                let indexPath = NSIndexPath(forRow: 0, inSection: 0)
                self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
                self.tableView.endUpdates()
                self.textField.text = ""
                self.textField.resignFirstResponder()



            })


        }})
    // Put the CloudKit private database in a constants
    let privateDatabase = CKContainer.defaultContainer().publicCloudDatabase

    // Create subscription and set three of its properties (an id, a predicate, and options)
    let friendsSubscription = CKSubscription(recordType: "Extra1",
        predicate: NSPredicate(format: "TRUEPREDICATE"),
        subscriptionID: "Extra1",
        options: .FiresOnRecordCreation)

    // Create a notification and set two of its properties (alertBody and shouldBadge)
    let notificationInfo = CKNotificationInfo()
    notificationInfo.alertBody = "New message in Lms Chat"
    notificationInfo.shouldBadge = false

    // Attach the notification to the subscription
    friendsSubscription.notificationInfo = notificationInfo

    // Save the subscription in the private database
    privateDatabase.saveSubscription(friendsSubscription) {recordReturned, error in
        // On the main thread, display an error/success message in the textView
        if error != nil {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                self.textField.text = "Cloud error\n\(error!.localizedDescription)"
            }
        } else {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                self.textField.text = ""
            }
        }
    }

}
func textFieldShouldEndEditing(textField: UITextField!) -> Bool {  //delegate method
    return false
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {   //delegate method
    textField.resignFirstResponder()

    return true

}

这是一个消息应用程序,因此人们可以互相发送消息,但我也希望他们接收通知。这是通知代码,我在 App Delegate 中也有一些通知代码:

import UIKit
    import CloudKit

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)

    UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)

    UIApplication.sharedApplication().registerForRemoteNotifications()

    return true
}


func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    let cloudKitNotification = CKNotification(fromRemoteNotificationDictionary: userInfo as! [String:NSObject])

    if cloudKitNotification.notificationType == CKNotificationType.Query {
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName("performReload", object: nil)
        })

    }

}

func resetBadge () {
    let badgeReset = CKModifyBadgeOperation(badgeValue: 0)
    badgeReset.modifyBadgeCompletionBlock = { (error) -> Void in
        if error == nil {
            UIApplication.sharedApplication().applicationIconBadgeNumber = 0
        }

    }

    CKContainer.defaultContainer().addOperation(badgeReset)
}


func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    resetBadge()

}

func applicationWillEnterForeground(application: UIApplication) {
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        NSNotificationCenter.defaultCenter().postNotificationName("performReload", object: nil)
    })
}

func applicationDidBecomeActive(application: UIApplication) {
    resetBadge()
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

但即使我拥有每次有人发送消息时发出通知所需的所有代码,也不会收到通知。我错过了什么吗?谢谢!

有人回答我之前说:

您正在向公共数据库添加数据,但您正在私有数据库上创建订阅。这两个中的一个需要更改以匹配另一个。

所以我把let privateDatabase = CKContainer.defaultContainer().privateCloudDatabase改成了let privateDatabase = CKContainer.defaultContainer().publicCloudDatabase

【问题讨论】:

  • 代码太多!请删除无关信息,方便我们调试
  • @penatheboss 它显示我的代码也许我做错了什么?
  • 不,你的代码没问题。只是太多了。只显示与您的问题相关的任何内容

标签: ios xcode swift notifications cloudkit


【解决方案1】:

在您的应用委托中,您缺少此方法:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    print(deviceToken)       // This is the device token
    var token: String = "\(deviceToken)"    /// formatted token.

    let rawtoken = token.stringByReplacingOccurrencesOfString(">", withString: "")
    let cleantoken = rawtoken.stringByReplacingOccurrencesOfString("<", withString: "")
    var finaltoken = cleantoken.stringByReplacingOccurrencesOfString(" ", withString: "")
    // Send device token to server

            }
        }
    }

我的意思是发送通知,你注册用户推送通知。对于这种情况,如果注册成功,则必须实现上述方法。 如果注册失败,你必须实现这个:

 func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print(error)

}

【讨论】:

  • 你能帮我解决这个问题吗? stackoverflow.com/questions/37495254/…
  • 嘿,我会帮忙的。我现在有点忙。
  • 我添加了您让我添加的内容,但通知仍然不显示。
  • 还有其他想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2018-02-27
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
相关资源
最近更新 更多