NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if(userInfo[@"aps"][@"url"])
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:userInfo[@"aps"][@"url"]]];
我想写这段代码在swift的推送通知。当我从服务器发送推送通知时,它不会显示在我的手机上。
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)!)
}
}
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)")
}
}
试试这个:
var userInfo = (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as! [NSObject : AnyObject])
if userInfo["aps"]["url"] {
UIApplication.sharedApplication().openURL(NSURL(string: userInfo["aps"]["url"])!)
}
以后参考:https://objectivec2swift.com/#/home/converter/