如何将目标 C 推送通知代码转换为 Swift
Posted
技术标签:
【中文标题】如何将目标 C 推送通知代码转换为 Swift【英文标题】:how to convert objective C push notification Code into Swift 【发布时间】:2016-08-22 10:19:07 【问题描述】: NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if(userInfo[@"aps"][@"url"])
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:userInfo[@"aps"][@"url"]]];
我想为推送通知快速编写此代码。当我从我的服务器发送推送通知时,它不会显示在我的手机上。
【问题讨论】:
【参考方案1】: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)!)
【讨论】:
【参考方案2】: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)")
【讨论】:
【参考方案3】:试试这个:
var userInfo = (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as! [NSObject : AnyObject])
if userInfo["aps"]["url"]
UIApplication.sharedApplication().openURL(NSURL(string: userInfo["aps"]["url"])!)
供日后参考:https://objectivec2swift.com/#/home/converter/
【讨论】:
以上是关于如何将目标 C 推送通知代码转换为 Swift的主要内容,如果未能解决你的问题,请参考以下文章
我必须将目标 c 代码转换为 swift 3.0,尝试在线转换时出错
如何将 Bitmap 转换为 AndroidBitmap 以在 Flutter 中推送通知?