前一篇轉載的文章說明了要如何生成cer 文件。在這個文章中,主要想記錄下,<span style="font-family: Arial, Helvetica, sans-serif;">AppDelegate 中要怎麼做。如下:</span>
//1.推送的形式:標記,聲音,提示
<strong> func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {</strong>
// Override point for customization after application launch.
initAPNs()
return true
}
//2. APNS
<strong> func initAPNs() {</strong>
print("AppDelegate.....initAPNs......")
let app = UIApplication.sharedApplication()
if DeviceUtils.isIOS7() {
let types: UIRemoteNotificationType = [UIRemoteNotificationType.Badge , UIRemoteNotificationType.Sound , UIRemoteNotificationType.Alert]
app.registerForRemoteNotificationTypes(types)
} else {
if #available(iOS 8.0, *) {
let types: UIUserNotificationType = [UIUserNotificationType.Badge , UIUserNotificationType.Sound , UIUserNotificationType.Alert]
let setting = UIUserNotificationSettings(forTypes: types, categories: nil)
app.registerUserNotificationSettings(setting)
app.registerForRemoteNotifications()
} else {
// Fallback on earlier versions
}
}
}
//3. 註冊成功保存 deviceToken
<strong>func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {</strong>
let apnDeviceTokens = deviceToken.toHexString() as String
let session = NSUserDefaults.standardUserDefaults()
session.setValue(apnDeviceTokens, forKey: "apn_device_token")
}
//4.處理推送消息
<strong> func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {</strong>
dealWithRemoteNotification(userInfo)
}
<strong>func dealWithRemoteNotification(userInfo: [NSObject : AnyObject]?) {</strong>
if UIApplication.sharedApplication().applicationState == UIApplicationState.Active {
return
}
let type = userInfo?["type"] as? String
if type == "follow" {
let user = userInfo?["user"] as? NSDictionary
if let uid = user?["id"] as? String {
gotoUserVCWith(uid)
}
} else if type == "live" {
let cast = userInfo?["cast"] as? NSDictionary
if let token = cast?["token"] as? String {
UIApplication.trackEvent(TrackEvent.CONTENT_CONSUMPTION, action: TrackEvent.VIDEO_SELECTED, label: "REMOTE_NOTIFICATION")
gotoVideoPlayerWith(token: token)
}
} else if type == "pick" {
let cast = userInfo?["cast"] as? NSDictionary
if let token = cast?["token"] as? String {
UIApplication.trackEvent(TrackEvent.CONTENT_CONSUMPTION, action: TrackEvent.VIDEO_SELECTED, label: "REMOTE_NOTIFICATION")
gotoVideoPlayerWith(token: token)
}
} else if type == "like" {
let cast = userInfo?["cast"] as? NSDictionary
if let token = cast?["token"] as? String {
UIApplication.trackEvent(TrackEvent.CONTENT_CONSUMPTION, action: TrackEvent.VIDEO_SELECTED, label: "REMOTE_NOTIFICATION")
gotoVideoPlayerWith(token: token)
}
} else if type == "link" {
if let target = userInfo?["target"] as? String {
let url: NSURL = NSURL(string: target)!
UIApplication.sharedApplication().openURL(url)
}
}
}