I want to run the function in the background. But I get an error. The error I received is
"nw_connection_receive_internal_block_invoke.
Why am I getting this problem? I'm trying it on an iOS 13 device. But I can't run the application in the background. I added a background run feature in Info.plist. I want to run the interator.tickTimer function in the background. But I'm getting an error. Does not work in the background. In the background, I want to periodically retrieve data from firebase.
import BackgroundTasks
#available(iOS 13.0, *)
extension AppDelegate {
func cancelAllPandingBGTask() {
BGTaskScheduler.shared.cancelAllTaskRequests()
}
func scheduleImageFetcher() {
let request = BGProcessingTaskRequest(identifier: "....")
request.requiresNetworkConnectivity = true // Need to true if your task need to network process. Defaults to false.
request.requiresExternalPower = false
request.earliestBeginDate = Date(timeIntervalSinceNow: 40)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule image featch: \(error)")
}
}
func handleAppRefreshTask(task: BGAppRefreshTask) {
task.expirationHandler = {
}
DispatchQueue.main.async {
let interator = MainTableViewController()
interator.tickTimer()
}
task.setTaskCompleted(success: true)
}
func handleImageFetcherTask(task: BGProcessingTask) {
scheduleImageFetcher() // Recall
//Todo Work
task.expirationHandler = {
}
task.setTaskCompleted(success: true)
}
}
xtension AppDelegate {
func registerLocalNotification() {
let notificationCenter = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
// print("User has declined notifications")
}
}
}
func scheduleLocalNotification() {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
self.fireNotification()
}
}
}
func fireNotification() {
// Create Notification Content
let notificationContent = UNMutableNotificationContent()
// Configure Notification Content
notificationContent.title = "Bg"
notificationContent.body = "BG Notifications."
// Add Trigger
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.0, repeats: false)
// Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "local_notification", content: notificationContent, trigger: notificationTrigger)
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
}
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13.0, *) {
registerBackgroundTaks()
registerLocalNotification()
} else {
// Fallback on earlier versions
}
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
if #available(iOS 13.0, *) {
cancelAllPandingBGTask()
scheduleImageFetcher()
} else {
// Fallback on earlier versions
}
}
//MARK: Regiater BackGround Tasks
#available(iOS 13.0, *)
private func registerBackgroundTaks() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "....-...", using: nil) { task in
//This task is cast with processing request (BGProcessingTask)
self.scheduleLocalNotification()
self.handleImageFetcherTask(task: task as! BGProcessingTask)
}
}
Related
BGAppRefreshTask is not working, I marked the option of background fetch capability
The method inside BGTaskScheduler.shared.register is never called
my code:
private let appRefreshTaskId = "internetDisconnectionsId"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13, *) {
BGTaskScheduler.shared.register(forTaskWithIdentifier: appRefreshTaskId, using: nil) { task in
self.handleAppRefreshTask(task: task as! BGAppRefreshTask)
}
}
return true
}
func handleAppRefreshTask(task: BGAppRefreshTask) {
task.expirationHandler = {
print("Background Working")
task.setTaskCompleted(success: true)
}
}
#available(iOS 13.0, *)
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: appRefreshTaskId)
request.earliestBeginDate = Date(timeIntervalSinceNow: 2 * 60) // Refresh after 2 minutes.
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh task \(error.localizedDescription)")
}
}
func sceneDidEnterBackground(_ scene: UIScene) {
(UIApplication.shared.delegate as! AppDelegate).scheduleAppRefresh()
print("called")
}
I would love to understand where I am wrong
Guys, I need your help, please.
What do I need: to get the tag's UID using iOS app
What do I have: I have an app Flutter, which works fine on Android (I can read the tag's UID) and do nothing on iOS
Details:
I have this type of cards (plastic card)
card's data, Mifare Classis 1k
As you can see, this is the Mifare Classic 1k card with payload "My text with spaces"
I used flutter channels to communicate between flutter and iOS native (swift)
On iOS side I created two implementations: one for NFCTagReaderSession, another one for NFCNDEFReaderSession (I do not use it at the same time, only separated)
1. NFCTagReaderSession implementation
import UIKit
import Flutter
import CoreNFC
#available(iOS 13.0, *)
var session_tag: NFCTagReaderSession?
#available(iOS 13.0, *)
var flutterResult: FlutterResult!
#available(iOS 13.0, *)
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate, NFCTagReaderSessionDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let nfcChannel = FlutterMethodChannel(name: "samples.flutter.dev/nfc", binaryMessenger: controller.binaryMessenger)
nfcChannel.setMethodCallHandler({
[weak self] (call: FlutterMethodCall, result: #escaping FlutterResult) -> Void in
// Note: this method is invoked on the UI thread.
guard call.method == "getNFCTag" else {
result(FlutterMethodNotImplemented)
return
}
if NFCTagReaderSession.readingAvailable {
print("we are ready for reading");
self?.startReadingNFC(result: result)
} else {
print("sorry byt not working");
}
})
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
private func startReadingNFC(result: #escaping FlutterResult) {
flutterResult = result
session_tag = NFCTagReaderSession(pollingOption: .iso14443, delegate: self, queue: DispatchQueue.main)
session_tag?.alertMessage = "Hold ur phone!"
session_tag?.begin()
}
func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {
print("Tag session active")
}
func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
print("Did detect tag reader session")
print(tags.count)
if case let NFCTag.miFare(tag) = tags.first! {
session.connect(to: tags.first!) { (error: Error?) in
let tagUIDData = tag.identifier
var byteData: [UInt8] = []
tagUIDData.withUnsafeBytes { byteData.append(contentsOf: $0) }
session.invalidate()
print(self.hexEncodedString(byteArray: byteData))
// DispatchQueue.main.async {
//flutterResult(self.hexEncodedString(byteArray: byteData))
// }
}
}
}
func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
print("Tag Error: \(error.localizedDescription)")
}
func hexEncodedString(byteArray: [UInt8]) -> String {
let hexDigits = Array("0123456789abcdef".utf16)
var hexChars = [UTF16.CodeUnit]()
hexChars.reserveCapacity(byteArray.count * 2)
for byte in byteArray {
let (index1, index2) = Int(byte).quotientAndRemainder(dividingBy: 16)
hexChars.append(hexDigits[index1])
hexChars.append(hexDigits[index2])
}
return String(utf16CodeUnits: hexChars, count: hexChars.count)
}
}
When i'm pressing the button in my app, i can see the NFC reading window on my phone
iOS app NFC reading window
But, when i put the card up to a phone, there is noting happened. Android Studio console
Android studio console
2. NFCNDEFReaderSession
import UIKit
import Flutter
import CoreNFC
#available(iOS 13.0, *)
var session_tag: NFCNDEFReaderSession?
#available(iOS 13.0, *)
var flutterResult: FlutterResult!
#available(iOS 13.0, *)
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate, NFCNDEFReaderSessionDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let nfcChannel = FlutterMethodChannel(name: "samples.flutter.dev/nfc", binaryMessenger: controller.binaryMessenger)
nfcChannel.setMethodCallHandler({
[weak self] (call: FlutterMethodCall, result: #escaping FlutterResult) -> Void in
// Note: this method is invoked on the UI thread.
guard call.method == "getNFCTag" else {
result(FlutterMethodNotImplemented)
return
}
if NFCNDEFReaderSession.readingAvailable {
print("we are ready for reading");
self?.startReadingNFC(result: result)
} else {
print("sorry byt not working");
}
})
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func startReadingNFC(result: #escaping FlutterResult) {
print("start reading session")
flutterResult = result
// session_tag = NFCNDEFReaderSession(pollingOption: [.iso14443], delegate: self, queue: DispatchQueue.main)
session_tag = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue.main, invalidateAfterFirstRead: false)
session_tag?.alertMessage = NSLocalizedString("Hold it!", comment: "my comment")
session_tag?.begin()
}
func tagReaderSessionDidBecomeActive(_ session: NFCNDEFReaderSession) {
print("Tag session active")
}
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
print(messages)
for message in messages {
for record in message.records {
print("next message")
print(record)
}
}
}
func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
if (tags.count > 0) {
session.connect(to: tags.first!, completionHandler: { (connection_error) in
tags.first?.readNDEF(completionHandler: { (message, error) in
if ((message?.records.count)! > 0) {
if let dataMessage = String(data: (message?.records.first!.payload)!, encoding:.utf8) {
session.invalidate()
print(dataMessage)
}
}
})
})
}
}
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
print("Tag Error: \(error.localizedDescription)")
}
func tagReaderSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
print("Tag Error: \(error.localizedDescription)")
// DispatchQueue.main.async {
// session.invalidate()
// print(error.localizedDescription)
// flutterResult(error.localizedDescription)
// }
}
}
After pressing the button in the app, NFC reading window also shows up. And with the card i can get the payload
Message: My message with spaces
Both approaches start fine and open the iOS's window with "read a tag", but with NFCTagReaderSession nothing is happening. It seems like there is no card. With NFCNDEFReaderSession implementation, I can read the message "My text with spaces" but, of course, I can't read the tag's UID
Am'I doing something wrong to get the UID of the card?
I am using FCM for push notification. FCM is connected, device is registered successfully and I am able to print device token but the device is not receiving notification.
In general -> capabilities tab -> enabled push notification and remote notification in back ground mode.
Here registering device for remote notification.
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let trimEnds:String! = {
deviceToken.description.trimmingCharacters(
in: CharacterSet(charactersIn: "<>"))
}()
let cleanToken:String! = {
trimEnds.replacingOccurrences(of: " ", with: "")
}()
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print(token)
UserDefaults.standard.set(token, forKey: "deviceToken")
UserDefaults.standard.synchronize()
#if DEBUG
//For Firebase
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
#else
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
#endif
print("Device Token:", token)
}
Here I called didReceiveRemoteNotification method to receive notification on the registered device:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("-=-=-=-=-\nDid receive notification\n-=-=-=-",userInfo)
print("-=-=-=-=-\n")
NotificationCenter.default.post(name: Notification.Name(rawValue: "notification_recieved"), object: nil)
if userInfo.index(forKey: "chat_id") != nil {
print("messag push")
if (AppUtility?.hasValidText(User.userID))! {
//let friendImage = userInfo["path"] as! String
let chatID = userInfo["chat_id"] as! String
let friendId = userInfo["to"] as! String
let unRead = userInfo["unread"] as! String
print(unRead)
UnReadMsgs = unRead
let dictAPS = userInfo["aps"] as! NSDictionary
let dict = dictAPS["alert"] as! NSDictionary
let friendName = dict["title"] as! String
let friendMsg = dict["body"] as! String
if(UIApplication.shared.applicationState == UIApplicationState.active){
print("app is Active")
if let wd = self.window {
var VC = wd.rootViewController
if(VC is UINavigationController){
VC = (VC as! UINavigationController).visibleViewController
if(VC is ChatViewController!){
print("Chat Screen")
let chatVC : ChatViewController = VC as! ChatViewController
if chatVC.chatId == chatID{
print("Same Chat")
self.clearChatWithChatID(chatID)
}else{
CustomNotificationView.showNotificationPopUp(self.window!, name: friendName, msg: friendMsg, image: "", chat: chatID, friendID: friendId)
playSound()
print("Other Chat")
}
}else{
let nc = NotificationCenter.default
nc.post(name: Notification.Name(rawValue: "MessageGet"),
object: nil,
userInfo: ["unRead":unRead,
"date":Date()])
CustomNotificationView.showNotificationPopUp(self.window!, name: friendName, msg: friendMsg, image: "", chat: chatID, friendID: friendId)
playSound()
print("Other Screen")
}
}
}
}else{
print("app is in BG")
var vc:ChatViewController!
vc = ChatViewController(nibName: "ChatViewController", bundle: nil)
vc.chatId = chatID
vc.otherUserId = friendId
vc.otherUserName = friendName
vc.channelRef = self.channelRef.child("\(chatID)")
vc.friendImageLink = "\(resourceUrl)\("")"
let nav = UINavigationController(rootViewController: vc)
nav.isNavigationBarHidden = false
if let wd = self.window {
var VC = wd.rootViewController
if(VC is UINavigationController){
VC = (VC as! UINavigationController).visibleViewController
}
VC!.present(nav, animated: false, completion: {
})
}
}
}
}else{
let val = userInfo["aps"] as! [String:AnyObject];
let alert = NSString(string: val["alert"] as! String)
if(UIApplication.shared.applicationState == UIApplicationState.inactive || UIApplication.shared.applicationState == UIApplicationState.background)
{
showUserInfo(application, didReceiveRemoteNotification: userInfo)
}
else
{
print("top most vc \(String(describing: UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentingViewController)) and presentedvc \(String(describing: UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentedViewController))")
if UIApplication.shared.keyWindow!.rootViewController!.topMostViewController() is NYAlertViewController{
let newAlert = AppUtility?.getDisplayAlertController(title: "FitFlow", messageText: alert as String)
let nvVc = UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentedViewController
nvVc?.present(newAlert!, animated: true, completion: nil)
return
}
AppUtility?.displayAlert(title:"FitFlow", messageText: alert as String,UIApplication.shared.keyWindow!.rootViewController!.topMostViewController())
}
}
}
I have tested by keeping breakpoints, it does not called didReceiveRemoteNotification method at all. How to receive push notification using above method?
I was also stuck with this earlier.
This requires FCM token, and not the APNS token.
To do so,
Your AppDelegate class needs to have these -
import Firebase
import UserNotifications
import FirebaseMessaging
class AppDelegate: UIResponder,
UIApplicationDelegate,
UNUserNotificationCenterDelegate,
FIRMessagingDelegate {
}
Then subscribe the messaging delegate in didFinishLaunchingWithOptions
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
GIDSignIn.sharedInstance().clientID =
"Your client id"
DispatchQueue.main.async {
FIRApp.configure()
}
FIRMessaging.messaging().remoteMessageDelegate = self
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
return true
}
// You dont need didRegisterForRemoteNotificationsWithDeviceToken method anymore
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { }
the token you received from the delegate didRegisterForRemoteNotificationsWithDeviceToken is not useful,
You need to use the FIRInstanceID.instanceID().token()
Add below code in your applicationDidBecomeActive, this will check for FCM token refreshes, and handle that elegantly.
func applicationDidBecomeActive(_ application: UIApplication) {
NotificationCenter.default.addObserver(self, selector:
#selector(tokenRefreshNotification), name:
NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
}
#objc func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
UserDefaults.standard.set(refreshedToken, forKey: "deviceToken")
self.sendFCMTokenToServer(token: refreshedToken)
}
/*
Connect to FCM since connection may
have failed when attempted before having a token.
*/
else {
connectToFcm()
}
}
func updatePushNotificationWebservice() {
/*
if you want to save that token on your server
Do that here.
else use the token any other way you want.
*/
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(String(describing: error))")
}
else {
print("Connected to FCM.")
/*
**this is the token that you have to use**
print(FIRInstanceID.instanceID().token()!)
if there was no connection established earlier,
you can try sending the token again to server.
*/
let token = FIRInstanceID.instanceID().token()!
self.sendFCMTokenToServer(token: token)
}
}
}
For debugging use the token obtained from FIRInstanceID.instanceID().token()!, and use the push notification firebase console with same token in the >project>Cloud messaging tab.
https://console.firebase.google.com/u/0/
Setting priority to high from backend solves my problem.
Please check from firebase console->cloud messaging(down left item) to send push notification.
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
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)
}
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().privateCloudDatabase
// 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!
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.