如何将Objective C push通知代码转换为Swift

时间:2016-08-22 10:19:08

标签: ios objective-c swift push-notification

 NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(userInfo[@"aps"][@"url"])
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:userInfo[@"aps"][@"url"]]];

我想在swift中编写此代码以进行推送通知。当我从我的服务器发送推送通知时,它不会显示在我的手机上。

3 个答案:

答案 0 :(得分:0)

if let userInfo = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {

    if var alertDict = userInfo["aps"] as? Dictionary<String, String> {
        let url = alertDict["url"]!
        UIApplication.sharedApplication().openURL(NSURL(string: url)!)
    }
}

答案 1 :(得分:0)

func registerForRemoteNotifications() {
        do {
        var types = [.Alert, .Badge, .Sound]
        var settings = UIUserNotificationSettings.settingsForTypes(types, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings!)
        UIApplication.sharedApplication().registerForRemoteNotifications()
    } 
}

//invoke when registeration of device is successfully
//get device token for push notification when device is registered

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        do {
        print("\(deviceToken)")
        var strDeviceToken = "\(deviceToken)"
        strDeviceToken = strDeviceToken.stringByReplacingOccurrencesOfString(" ", withString: "")
        strDeviceToken = strDeviceToken.stringByReplacingOccurrencesOfString("<", withString: "")
        strDeviceToken = strDeviceToken.stringByReplacingOccurrencesOfString(">", withString: "")
        NSUserDefaults.standardUserDefaults().setValue(strDeviceToken, forKey: NOTIFICATION_DEVICE_TOKEN)
        print("Successfully registered for remote notifications With device Token \(strDeviceToken)")
    } 
}

//invoke when registeration of device is failed

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError?) {
        do {
        print("Notification registration failed reason:-\(error.localizedDescription)")
    }     catch let exception {
        print("Exception in fun:\(__func__) line:\(__LINE__) reason:\(exception.reason)")
    } 
}

//invoke when push notification is received

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        do {
        print("userInfo:-\(userInfo)")
    }     catch let exception {
        print("Exception in fun:\(__func__) line:\(__LINE__) reason:\(exception.reason)")
    } 
}

答案 2 :(得分:0)

试试这个:

var userInfo = (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as! [NSObject : AnyObject])
if userInfo["aps"]["url"] {
    UIApplication.sharedApplication().openURL(NSURL(string: userInfo["aps"]["url"])!)
}

供将来参考:https://objectivec2swift.com/#/home/converter/