【问题标题】:Azure + Swift Push NotificationsAzure + Swift 推送通知
【发布时间】:2015-05-06 12:49:45
【问题描述】:

我正在尝试从远程服务器向应用程序进行非常简单的推送。

我已按照 [1] 在 Azure 上设置了一个通知中心,但我无法将调试消息发送到设备。 我不想使用移动服务从数据库表读取/写入数据

我在 Swift 中执行此操作,并且我在互联网上发现 nothing 实际上从服务器接收推送是 iOS swift 作为完整教程。

我不知道,例如,如何用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);
        }
    }];
}

到目前为止,这是我在 AppDelegate 中的代码(我从 [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!")
}

我得到一个设备令牌,这意味着我应该注册,但我不知道如何正确实现[代码]

self.client?.push.registerNativeWithDeviceToken(deviceToken: deviceToken, tags: registrationTags, completion: [code])

EDIT 1我在这里取得了一些进展:

self.client?.push.registerNativeWithDeviceToken(deviceToken, tags: registrationTags, completion: { (error) -> Void in
        println("Error registering")
    })

现在注册时出现错误:

错误域=com.Microsoft.WindowsAzureMobileServices.ErrorDomain 代码=-1302“错误:内部服务器错误”UserInfo=0x14d97b10 {NSLocalizedDescription=错误:内部服务器错误,com.Microsoft.WindowsAzureMobileServices.ErrorResponseKey= { URL:https://[servicename].azure-mobile.net/push/registrations%3FdeviceId=[longnumber]&platform=apns } { 状态码:500,标题 { “缓存控制”=“无缓存”; “内容长度”= 51; “内容类型”=“应用程序/json”; 日期 =“格林威治标准时间 2015 年 3 月 5 日星期四 08:52:10”; 服务器 = "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 }}

编辑 2

我现在在阅读[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)")
        })
    }

我现在看到的输出是:

获得设备令牌
注册错误:无

我觉得我正在取得进展,但是当我从 Azure 发送调试推送时,我的日志中什么也看不到(目前当我收到推送时,我只是打印一条消息)

参考:
[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/

【问题讨论】:

  • 您的 deviceToken 是 NSData 类型,请将其转换为 NSString 后再使用。
  • 但是 registerNativeWithDeviceToken 的签名实际上想要的是 NSData!输入...
  • let token = NSString(data: deviceToken, encoding: NSUTF8StringEncoding)//结果为零,即使我返回的是 NSInlineData 类型的 32 字节数据
  • 从 deviceToken 中移除 angle brackets
  • 你能指出尖括号吗?

标签: ios swift azure push-notification


【解决方案1】:

这对我来说很好用:

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

})

【讨论】:

    【解决方案2】:

    这个对我有用。希望这可能会有所帮助。

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

    【讨论】:

    • 我无法告诉你这是否是答案......我想如果它得到足够的支持,我会将其标记为答案。老实说,我尝试了几个不同的推送提供程序,他们立即工作。
    • 您无需将此标记为答案。我刚刚遇到了同样的问题,并从您的尝试中得到了帮助。谢谢。
    • 您好 - 我想将某事标记为答案 - 我相信这是良好的社区礼仪(如果我有问题的答案但不接受答案,它也会影响我的统计数据)。我很高兴我们互相帮助 :) 您是否发现 Azure 的推送始终如一?我确实让他们工作了,但大约 50 人中有 1 人通过了。可能是因为我在南非,出于某种原因,第一世界无法理解我们是一个能够工作的人不仅仅是一个门铃(在 Google Play 商家帐户上的戳戳、iStore 存在等 - 此处不可用)
    • 对我来说,10 条消息中大约有 8-9 条消息通过。我认为 50 条中的 1 条消息太糟糕了:( 据我记得,如果消息内容是,它不会推送通知一样。所以,我每次发送测试消息时都会更改消息内容。
    • 请问您在 Azure 管理控制台的哪个位置获取应用密钥?
    猜你喜欢
    • 2015-05-12
    • 1970-01-01
    • 2016-10-27
    • 2016-04-24
    • 2017-10-10
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多