当前位置: 首页 > 知识库问答 >
问题:

Azure Swift推送通知

经福
2023-03-14

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

我已根据[1]在Azure上设置了通知中心,但我无法获取设备的调试消息。我不想使用移动服务从DB表读/写

我在Swift中这样做,但我在互联网上没有发现任何真正从服务器接收推送的是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])

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

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

现在我注册时出错:

错误域=com. Microsoft. WindowsAzureMobileServices. ErrorDomain Code=-1302"错误:内部服务器错误"UserInfo=0x14d97b10{NSLocalizedDescription=错误:内部服务器错误,com. Microsoft. WindowsAzureMobileServices.错误响应键={URL: https://[servicename].azure-mobile.net/push/registrations?deviceId=[longnumber]

编辑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]在swift中注册iOS7个通知
[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/

共有2个答案

段曦
2023-03-14

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

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)
}
鲜于宏义
2023-03-14

这对我来说很好:

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

})
 类似资料:
  • 首先,我想声明我一直在研究推送通知和web通知之间的关系,但我有点困惑。 我从这里读到PWAs的推送通知在Safari上的iOS(iPhone)不起作用:从PWA向iOS发送推送通知 然而,如果iPhone用户使用的是Chrome,这是否意味着它们可以工作呢?或者推送通知在任何浏览器上对iPhone中的PWAs都不起作用? 这就把我带到了web通知。web通知在后台对PWAs起作用吗?我的问题是w

  • 如何通过Azure从我的UWP-App向不同设备上的应用程序的其他实例发送推送通知? 以下是注册设备以接收推送的说明。(这是可行的)第二部分是关于如何在控制台应用程序上发送推送(这也是可行的)https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-windows-store-dotnet-get-star

  • 通过上面的行,我得到了一个URL,它将在大约一个月内有用。 现在我不可能做的是将推送通知发送到应用程序。 任何关于如何使用Uri和如何将信息发送到它的光我会很高兴,因为我的400错误,那是关于我的post消息的一些错误。 我可以在发布或调试模式下获得推送通知吗? 使用PHP可以完成带有正确Uri的推送通知吗?

  • 我有一些关于实现推送通知的问题。事情是, > 订阅对象中的所有数据都是必需的吗?或者只有终点。 如果用户登录的设备超过10台,我是否需要为每个设备存储订阅值?是这样的吗?还是应该存储上次登录设备的订阅值?如果是这样,那么其余9个将不会收到任何通知。 如果您正在存储所有loggedin设备的订阅值,那么用户是否登录了多个浏览器?他会在每个浏览器中收到通知吗?这是标准做法吗? 欢迎提出建议,任何标准做

  • 问题内容: 我正在开发一个应用程序,在该应用程序中,我需要实现推送通知。谁能建议我应该如何实施推送通知?如果可以为我提供一个很好的教程,那就太好了! 谢谢。 问题答案: //在应用程序启动时调用 //清单文件中的更改 // ReceiverC2DM.java ..... //服务器端…新测试应用 ServerSimulator.java

  • 我使用城市飞艇在iOS 10(Swift)应用程序中接收推送通知。我遇到以下问题,请您帮助解决。 应用程序运行时无法隐藏通知 为了隐藏通知,我尝试了以下任务... > 删除委托方法func userNotificationCenter的实现(center:UNUserNotificationCenter,willPresent通知:UNNotification,withCompletionHand