Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure + Swift Push Notifications

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/

like image 226
Quintin Balsdon Avatar asked Feb 11 '23 18:02

Quintin Balsdon


1 Answers

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

})
like image 153
Allan Scofield Avatar answered Feb 13 '23 06:02

Allan Scofield