34033

SWIFT: I don't get notifications from my CloudKit app?

Question:

Here is my code:

@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 }

It's a messaging app so people can message eachother but I also want them to recieve notifications. This is the code for notifications and I also have some code for notifications in 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:. } }

But notifications do not come in even though I have all of the code needed to make notifications every time someone sends a message. Am I missing something? Thanks!

Someone answered me before saying:

You are adding data to the public database but you are creating your subscription on the private database. One of those two needs to be changed to match the other.

So I changed the let privateDatabase = CKContainer.defaultContainer().privateCloudDatabase to let privateDatabase = CKContainer.defaultContainer().publicCloudDatabase

Answer1:

In your app Delegate, you are missing this method :

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 } } }

WHat I mean is that to send notification, you register user for push Notification. For the case If the register succeeds, you have to implement the method above. if the registeration fails, you have to implement this :

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

Recommend

  • Can a desire2learn remote plugin be used to insert a custom external learning tool link into a cours
  • NullPointerException while creating Jasper Report
  • Selecting Percentile curves using gamlss::lms in R
  • Openedx Native installation : theme change not working
  • CKSubscription of type CKSubscriptionOptionsFiresOnRecordUpdate doesn't work
  • JSON Array to ImageView in GridView
  • Do I need to set Internet permission for opening a website in Android?
  • Android incremented counters wont reset?
  • How to acces variable in arrayadapter getView from onItemClick
  • iPhone: Stop UIScrollView from auto scrolling when UITextView text is changed
  • ListView performance is slow
  • how to passing listview images passing another activity [closed]
  • Show progress of seekbar in a textview inside a custom alert dialog
  • Firebase - retrieve data in Android
  • What other Adapters can I use for ListView?
  • List view crashes when scrolling “The application may be doing too much work on its main thread.”
  • Listview with multiple strings
  • How to mount dynamically single file component in Vue.js
  • LatLong falls within a given polygon in D3 + Leaflet
  • Detect when user takes a screen shot in windows with print screen?
  • Remove every nth element from swift array
  • XMPPConnection Error in android
  • android.app.PendingIntent cannot be accessed ouside the package
  • Fancy dynamic list in Android: TableLayout vs ListView
  • Trouble Attaching Call Back to Unobtrusive Validation Show Error
  • Why does .addView throw this parent/child exception?
  • How to Handle Click on Imageview in Custom Listview with image and Textview?
  • Is it possible to send skype chat messages from a linux server without X?
  • Null ImageView Reference
  • C#: Import/Export Settings into/from a File
  • How can I set a binding to a Combox in a UserControl?
  • AJAX Html Editor Extender upload image appearing blank
  • Bug in WPF DataGrid
  • In LanguageTool, how do you create a dictionary and use it for spell checking?
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Cannot Parse HTML Data Using Android / JSOUP
  • Bitwise OR returns boolean when one of operands is nil
  • sending mail using smtp is too slow
  • costura.fody for a dll that references another dll
  • Binding checkboxes to object values in AngularJs