I am trying to make a VERY simple PUSH from a remote server to an app.
I have set up a notification hub on Azure as per [1], but I cannot get a debug message down to the device. I DO NOT WANT TO READ / WRITE FROM A DB TABLE USING MOBILE SERVICES
I am doing this in Swift, and I have found nothing on the internet that actually receives a push from a server is iOS swift as a complete tutorial.
I do not know, for example, how to write the following code in swift:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// TODO: update #"MobileServiceUrl" and #"AppKey" placeholders
MSClient *client = [MSClient clientWithApplicationURLString:#"MobileServiceUrl" applicationKey:#"AppKey"];
[client.push registerNativeWithDeviceToken:deviceToken tags:#[#"uniqueTag"] completion:^(NSError *error) {
if (error != nil) {
NSLog(#"Error registering for notifications: %#", error);
}
}];
}
So far this is my code in my AppDelegate (some of the code I got from [2]):
var client: MSClient?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if(UIApplication.instancesRespondToSelector(Selector("registerUserNotificationSettings:")))
{
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
}
/*else
{
//do ios7 stuff here. If you are using just local notifications then you dont need to do anything. for remote notifications:
application.registerForRemoteNotificationTypes(UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge)
}*/
self.client = MSClient(applicationURLString: "[url]", applicationKey: "[key]")
UIApplication.sharedApplication().registerForRemoteNotifications()
let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
println("Got device token \(deviceToken)");
//IS THIS EVEN CORRECT???? [3] and [4]
/*let json = ("{\"platform\":\"ios\", \"deviceToken\":\"\(deviceToken)\"}" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
self.client?.invokeAPI("register_notifications", data: json, HTTPMethod: "POST", parameters: nil, headers: nil, completion:nil)*/
let registrationTags: [String] = ["tag"];
//EDIT 1 - I HAVE MADE A LITTLE PROGRESS
self.client?.push.registerNativeWithDeviceToken(deviceToken, tags: registrationTags, completion: { (error) -> Void in
println("Error registering")
})
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("Could not register \(error)");
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
println("Remote notification received!")
println("Awesome!")
}
I am getting a device token back, which means I should be registered, but I do not know how to properly implement [code]
self.client?.push.registerNativeWithDeviceToken(deviceToken: deviceToken, tags: registrationTags, completion: [code])
EDIT 1 I have made some progress here:
self.client?.push.registerNativeWithDeviceToken(deviceToken, tags: registrationTags, completion: { (error) -> Void in
println("Error registering")
})
Now I get an error with registering:
Error Domain=com.Microsoft.WindowsAzureMobileServices.ErrorDomain Code=-1302 "Error: Internal Server Error" UserInfo=0x14d97b10 {NSLocalizedDescription=Error: Internal Server Error, com.Microsoft.WindowsAzureMobileServices.ErrorResponseKey= { URL: https://[servicename].azure-mobile.net/push/registrations%3FdeviceId=[longnumber]&platform=apns } { status code: 500, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 51;
"Content-Type" = "application/json";
Date = "Thu, 05 Mar 2015 08:52:10 GMT";
Server = "Microsoft-IIS/8.0";
"Set-Cookie" = "ARRAffinity=[somehash];Path=/;Domain=[servicename].azure-mobile.net";
"X-Powered-By" = "ASP.NET";
"x-zumo-version" = "Zumo.master.0.1.6.4217.Runtime";
} }, com.Microsoft.WindowsAzureMobileServices.ErrorRequestKey= { URL: https://[servicename].azure-mobile.net/push/registrations%3FdeviceId=[longnumber]&platform=apns }}
EDIT 2
I have now made the following changes after reading [5]:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let token = NSString(data: deviceToken, encoding: NSUTF8StringEncoding)
println("Got device token");
let hub = SBNotificationHub(connectionString: CONNECTIONSTRING, notificationHubPath: HUBPATH)
hub.registerNativeWithDeviceToken(deviceToken, tags: nil, completion: {(error) -> Void in
println("Error registering: \(error)")
})
}
And the output I now see is:
Got device token
Error registering: nil
I feel like I am making progress but when I send the debug push from Azure I see nothing in my logs (currently when I receive a push I just print a message)
References:
[1] http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-ios-get-started/
[2] Registering for iOS 7 notifications in swift
[3] https://github.com/Azure/azure-content/blob/master/articles/notification-hubs-ios-mobile-services-register-user-push-notifications.md
[4] http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-ios-mobile-services-register-user-push-notifications/
[5] http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-ios-get-started/
This worked fine for me:
let client: MSClient = MSClient(applicationURLString: "https://yoururl.azure-mobile.net/", applicationKey: "yourApplicationKey")
client.push.registerNativeWithDeviceToken(deviceToken, tags: nil, completion: {(error) -> Void in
if error != nil{
NSLog("Error registering for notifications: %#", error)
}
})
This one worked for me. Hope this may help.
var client: MSClient?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
#if !TARGET_IPHONE_SIMULATOR
let notiType:UIUserNotificationType = .Alert | .Badge | .Sound
let settings = UIUserNotificationSettings(forTypes: notiType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
#endif
self.client = MSClient(applicationURLString:"https://yourAppName.azure-mobile.net/", applicationKey:"yourApplicationKey")
return true
}
func application(application: UIApplication!, didFailToRegisterForRemoteNotificationsWithError error: NSError!) {
println("Failed to register with error: \(error)");
}
func application(application: UIApplication!, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData!) {
let hub = SBNotificationHub(connectionString:"yourConnectionString", notificationHubPath:"yourAppName")
hub.registerNativeWithDeviceToken(deviceToken, tags:nil, completion: { (error) in
if (error != nil) {
println("Error registering for notification: \(error)")
}
})
}
func application(application: UIApplication!, didReceiveRemoteNotification userInfo:[NSObject : AnyObject]?, fetchCompletionHandler:()) {
println("Recived: \(userInfo)")
NSNotificationCenter.defaultCenter().postNotificationName("ReceivedNotification", object:userInfo)
}
Related
I'm new to iOS software development and swift and I'd like to make an app that is similar to instagram. For this I created a VM instance in google cloud with the Network tags parse-1-tcp-443, parse-1-tcp-80. I ran the code above in the newest version of xcode and got those errors. Why do I get unauthorized error when after logging in username, password url are correct?
Allow Arbitrary Loads is set to yes in info.plist
Thanks in advance!
import UIKit
import Parse
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.enableLocalDatastore()
let parseConfiguration = ParseClientConfiguration(block: { (ParseMutableClientConfiguration) -> Void in
ParseMutableClientConfiguration.applicationId = "user"
ParseMutableClientConfiguration.clientKey = "*********"
ParseMutableClientConfiguration.server = "http://35.19.10.151/parse"
})
Parse.initialize(with: parseConfiguration)
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
defaultACL.getPublicReadAccess = true
PFACL.setDefault(defaultACL, withAccessForCurrentUser: true)
if application.applicationState != UIApplicationState.background {
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let installation = PFInstallation.current()
installation.setDeviceTokenFrom(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannel(inBackground: "") { (succeeded, error) in // (succeeded: Bool, error: NSError?) is now (succeeded, error)
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %#.\n", error)
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#\n", error)
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handle(userInfo)
if application.applicationState == UIApplicationState.inactive {
PFAnalytics.trackAppOpened(withRemoteNotificationPayload: userInfo)
}
}
}
Error:
2017-10-25 13:08:47.984583+0200 ParseStarterProject-Swift[28036:1825625] [Error]: unauthorized (Code: 0, Version: 1.12.0)
Optional(Error Domain=Parse Code=0 "unauthorized" UserInfo={error=unauthorized, NSLocalizedDescription=unauthorized, temporary=0})
If I write "http://35.19.10.151/" instead of "http://35.19.10.151/parse" I get this:
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})
I include google firebase in my app - create google account, create google app, upload APNS certifications (.pem and in work in another service), and send push notifications from console, and my app not receive it. In Firebase console i see status complete but Approximate number of devices is "-"
Of course I updated provisions profiles and APNS cert
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Register for remote notifications
if #available(iOS 8.0, *) {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// Fallback
let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
application.registerForRemoteNotificationTypes(types)
}
FIRApp.configure()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
name: kFIRInstanceIDTokenRefreshNotification, object: nil)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
func tokenRefreshNotificaiton(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
User.sharedUser.googleUID = refreshedToken
}
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
print(userInfo)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
print(userInfo)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("ошибка")
print(error)
print(error.description)
}
The first thing I see is there's no call to connect to FIRMessaging. Try adding this to your AppDelegate:
func applicationDidBecomeActive(application: UIApplication) {
FIRMessaging.messaging().connectWithCompletion { error in
print(error)
}
}
Use the following code.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
if #available(iOS 10.0, *)
{
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert]) { (granted, error) in
if granted
{
//self.registerCategory()
}
}
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
}
else
{
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
//Configuring Firebase
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)
return true
}
//Receive Remote Notification on Background
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
}
func tokenRefreshNotification(notification: NSNotification)
{
if let refreshedToken = FIRInstanceID.instanceID().token()
{
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func connectToFcm()
{
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil)
{
print("Unable to connect with FCM. \(error)")
}
else
{
print("Connected to FCM.")
}
}
}
func applicationDidBecomeActive(application: UIApplication)
{
connectToFcm()
}
You might be using Data or aps key in PUSH JSON which is used to send notifications to devices. It should work properly but in rare cases, it not works, even it'll give you success in fcm/send api but notification will not reach particular devices. This problem usually occurs in iOS devices.
A solution which worked for me is add notification key instead of Data.
{
"to" : "device token",
"notification":{
"body": "test",
"title": "test"
}
}
If you are sending from Backend OR you don't have access of Firebase console. Then you can test and send notification via POSTMAN also. But you must have SERVER KEY, which can be got from Firebase console under Cloud Messaging settings.
API: https://fcm.googleapis.com/fcm/send
Method: POST
Headers:
"Content-Type"=application/json
"Authorization"="key=YOUR SERVER KEY" //You must add key= above the server key.
{
"to" : "your device token",
"notification":{
"body": "test",
"title": "test"
}
}
ANOTHER DETAILED AND FULL PAYLOAD IF YOU NEED TO SEE WHAT WE CAN SEND IN FIREBASE NOTIFICATION:
{
"to":"device token",
"notification":{
"data":{
"avatar":"",
"body":"",
"key_notification":"0",
"type_notification":"1",
"deviceToken":"device token",
"badge":1,
"message":"your text"
},
"text":"your text",
"sound":"sound.caf",
"badge":21
},
"priority":"high"
}
Using GCM for push notification in iOS. Everything is set up nicely. I'm getting registrationToken value & also subscribeToTopic successfully. Connected to GCM. didRegisterForRemoteNotificationsWithDeviceToken method also called. But not getting push notification. didReceiveRemoteNotification method never called. On my android app I'm getting the push notification without any problem. But in iOS notification never received. Here is the source code:
class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate{
var gcmSenderID: String?
var registrationToken: String?
let registrationKey = "onRegistrationCompleted"
let messageKey = "onMessageReceived"
var registrationOptions = [String: AnyObject]()
var connectedToGCM = false
let subscriptionTopic = "/topics/global"
var subscribedToTopic = false
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID
if application.respondsToSelector("registerUserNotificationSettings:") {
let types:UIUserNotificationType = (.Alert | .Badge | .Sound)
let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// Register for Push Notifications before iOS 8
application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}
let gcmConfig = GCMConfig.defaultConfig()
gcmConfig.receiverDelegate = self
GCMService.sharedInstance().startWithConfig(gcmConfig)
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("remote notification")
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
}
func application( application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
userInfo: userInfo)
handler(UIBackgroundFetchResult.NoData);
}
func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
deviceToken: NSData ) {
let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
instanceIDConfig.delegate = self
GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig)
registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:true]
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
// [END get_gcm_reg_token]
}
func onTokenRefresh() {
// A rotation of the registration tokens is happening, so the app needs to request a new token.
print("The GCM registration token needs to be changed.")
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
}
func registrationHandler(registrationToken: String!, error: NSError!) {
if (registrationToken != nil) {
self.registrationToken = registrationToken
print("Registration Token: \(registrationToken)")
self.subscribeToTopic()
let userInfo = ["registrationToken": registrationToken]
NSNotificationCenter.defaultCenter().postNotificationName(
self.registrationKey, object: nil, userInfo: userInfo)
} else {
print("Registration to GCM failed with error: \(error.localizedDescription)")
let userInfo = ["error": error.localizedDescription]
NSNotificationCenter.defaultCenter().postNotificationName(
self.registrationKey, object: nil, userInfo: userInfo)
}
}
func subscribeToTopic() {
// topic
if(registrationToken != nil && connectedToGCM) {
GCMPubSub.sharedInstance().subscribeWithToken(self.registrationToken, topic: subscriptionTopic,
options: nil, handler: {(NSError error) -> Void in
if (error != nil) {
// Treat the "already subscribed" error more gently
if error.code == 3001 {
print("Already subscribed to \(self.subscriptionTopic)")
} else {
print("Subscription failed: \(error.localizedDescription)");
}
} else {
self.subscribedToTopic = true;
NSLog("Subscribed to \(self.subscriptionTopic)");
}
})
}
}
func applicationDidBecomeActive(application: UIApplication) {
print("applicationDidBecomeActive")
self.globalPrice = CartLocalData.getTotalPrice()
GCMService.sharedInstance().connectWithHandler({
(NSError error) -> Void in
if error != nil {
print("Could not connect to GCM: \(error.localizedDescription)")
} else {
self.connectedToGCM = true
self.subscribeToTopic()
print("Connected to GCM")
// ...
}
})
}
}
What am I doing wrong. Can anyone suggest??
you should have the option to turn on push from capabilities section. You also need to build separate key/cert pair in the apple member center and have those included on your machine. here is a screenshot from a new project i made.
It sounds like maybe one of the steps in the process might not be done.
Start over again and try to figure out what your missing. here is a ray wenderlich tutorial that walks you through the steps here
And the link to Apple developer site that talks about it in depth here
I am trying to add the current user to the installation class, but for some reason the function is not being called. What am I doing wrong? How do I fix this? Below is both the finishlaunchingwithoptions and didregisterfornotifications.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.enableLocalDatastore()
// Initialize Parse.
Parse.setApplicationId("***********************",
clientKey: "****************************")
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
if let launchOptions = launchOptions as? [String : AnyObject] {
if let notificationDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] {
self.application(application, didReceiveRemoteNotification: notificationDictionary)
}
}
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Store the deviceToken in the current Installation and save it to Parse
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation["user"] = PFUser.currentUser()
installation.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if (error == nil){
print("saved installation")
}else{
print(error)
}
})
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError!) {
print("Couldn't register: \(error)")
}
The problem in this situation is that you're running in the iOS Simulator, which does not support remote notifications. So, your didRegisterForRemoteNotificationsWithDeviceToken will never be called, because you're in the simulator. Try on a device and I suspect it will work first time.
For future readers who find this and have a similar problem, the best way to diagnose the problem is to add this to your app delegate:
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Failed to register for remote notifications: \(error.localizedDescription)");
}
I recommend accomplishing this using a cloud code beforeSave trigger on the Installation class. It's incredibly simple and more robust than trying to handle it client-side. Here's all you need to get the job done:
// Make sure all installations point to the current user
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) {
Parse.Cloud.useMasterKey();
if (request.user) {
request.object.set('user', request.user);
} else {
request.object.unset('user');
}
response.success();
});
I have problem with GCM and ios push notificaion.
App connect to GCM and all that works but when i can't receive notification.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let gcmSenderID = sharedUser.getGcmSenderId()
if gcmSenderID?.characters.count > 0 {
var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
if configureError != nil {
print("Error configuring the Google context: \(configureError)")
}
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
GGLInstanceID.sharedInstance().startWithConfig(GGLInstanceIDConfig.defaultConfig())
registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:true]
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
}
func registrationHandler(registrationToken: String!, error: NSError!) {
if (registrationToken != nil) {
let params = [
"reg_id": registrationToken,
"dev_id": UIDevice.currentDevice().identifierForVendor!.UUIDString
]
Alamofire.request(.POST, Config().gcmRegUrl, parameters: params, encoding: .JSON)
print("Registred")
} else {
print("Registration to GCM failed with error: \(error.localizedDescription)")
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
print("Message")
}
This didReceiveRemoteNotification never fires, and i am sure that server send message.
What can be problem?
Thanks to Arthur Thompson, needed this:
func applicationDidBecomeActive(application: UIApplication) {
GCMService.sharedInstance().connectWithHandler({
(NSError error) -> Void in
if error != nil {
print("Could not connect to GCM: \(error.localizedDescription)")
} else {
print("Connected to GCM")
}
})
}
And i forgot:
GCMService.sharedInstance().startWithConfig(GCMConfig.defaultConfig())
to add on didFinishLaunchingWithOptions.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let gcmSenderID = sharedUser.getGcmSenderId()
if gcmSenderID?.characters.count > 0 {
var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
if configureError != nil {
print("Error configuring the Google context: \(configureError)")
}
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
GCMService.sharedInstance().startWithConfig(GCMConfig.defaultConfig())
}
}
Now everything works..