雖然通知經常被過度使用,但是通知確實是一種獲得用戶關注和通知他們需要更新或行動的有效方式。iOS 10有了新的通知,如新消息、商業信息和時間表的變化。在本教程中,我將向你展示如何使用通知在你的iOS應用程序,並且顯示iOS 10引入了新特性。開發iOS 10推送通知你需要最新版本的Xcode,Xcode 8測試版,這些目前都是可下載的,在下載頁面。
你可以去Github下載本教程的整個工程。
開始
在Xcode中啓用推送通知是很容易的,但你需要幾個步驟。
創建一個新的工程,給它起一個唯一的Bundle Identifier.
當您已經創建了project,去Project Settings頁選擇Capabilities欄。打開推送通知,如下所示。
注意: 如果你是蘋果的付費開發者成員,你就能看到推送通知功能這一欄。
去Developer Account這一欄,從左側的菜單欄中選擇證書,IDs,和描述文件,然後選擇App IDs在Identifiers欄中。找到已經創建的App的名稱,在服務列表中選中。注意,有兩個可配置狀態的推送通知。
不要關閉這個網頁,你很快就會回來的。
發送通知
在本文中,我將使用Pusher發送推送通知。您還可以使用其他的解決方案如Houston。無論哪種方式,發送一個通知,你都需要一個證書。
去創建一個證書,打開Keychain Access,從證書認證菜單中選擇Keychain Access -> Certificate Assistant -> Request a Certificate。
填寫表單並單擊Continue。確保你選擇保存到了磁盤。
返回到開發者賬戶的網頁。你可以爲你的App IDs生成開發(調試)證書或發佈證書。
之後在選擇右側的申請,在底部,單擊編輯。在推送通知部分,單擊創建開發(調試)證書。
在需要時,從Keychain,繼續上傳生成證書請求。
現在你已經創建了證書,可以下載它。打開下載的文件安裝它。
下載並運行Pusher。這個程序的頂部需要填入一個推送的證書。爲它位於你的鑰匙鏈,OS X將詢問是否允許Pusher訪問證書。
第二個字段需要device token,你會在下一步中得打它。
收到通知
是時候敲代碼了。收到通知的設備必須註冊到蘋果推送通知服務(APNS)。在應用啓動的時候你要發送一個唯一的token。
打開AppDelegate.swift然後添加如下方法。
注意:該代碼是基於Swift3.0。語法可能看起來不同於你之前使用過的。
func registerPushNotifications() {
DispatchQueue.main.async {
let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
UIApplication.shared().registerUserNotificationSettings(settings)
}
}
我之後會解釋,在這個設置中你會收到指定的通知類型。調用這個方法在應用程序啓動的的文件裏。
1
2
3
4
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
registerPushNotifications()
return true
}
此時,應用程序將自動彈出一個Alert,詢問用戶是否要收到該通知。
通知必須被註冊,才能發送,而是否接受通知則需要用戶批准。UIApplicationDelegate方法處理響應。
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != UIUserNotificationType() {
application.registerForRemoteNotifications()
}
}
首先檢查用戶授予權限,然後調用該方法註冊遠程通知。當請求完成後者將調用另一個代理方法。這個方法響應包含一個device token,你可以打印進行調試。在發送推送通知來識別設備需要這個device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let chars = UnsafePointer((deviceToken as NSData).bytes)
var token = ""
for i in 0..<devicetoken.count { token +=" String(format: ".2hhx", arguments: [chars[i]])" }="" print("registration succeeded!")="" print("token: ", token)="" }<="" pre=""><p>如果出現錯誤,調用下面的方法。</p><pre class="brush:js;toolbar:false">func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Registration failed!")
}</pre><p>注意:重要的是在應用程序啓動時要調用registerUserNotificationSettings,因爲用戶可以改變權限的設置。同樣registerForRemoteNotifications也是很重要的,因爲有些場景device token可以改變那麼通知將不再發送。</p><p>到目前爲止,這足以讓你收到一個簡單的通知。</p><p><strong>通知內容</strong></p><p>通過不同的通知內容,有不同的方式來使一個App來收到不同類型的通知,這些通知內容包括應用程序通知用戶的信息,或者用戶自定義的信息。</p><p>給用戶發送通知,使用JSON格式,這個格式本身包含一個字典,對應aps的key。在這第二個字典你指定載內容和key。</p><p>最常見的是:</p><ul class=" list-paddingleft-2"><li><p>向用戶顯示的通知消息。這是一個簡單的字符串,或一個字典key和標題一樣,正文等等。</p></li><li><p>接收到通知的聲音。它可以是一個定製的聲音,或一個系統的聲音。</p></li><li><p>應用圖標右上角的角標個數。將其設置爲0,消除角標。</p></li><li><p>有效的內容。使用值1發送一個無聲的通知給用戶。它不會播放任何聲音,或任何角標設置,但是當通知被喚醒,應用將與服務器進行溝通。</p></li></ul><p>本教程的一個簡單的通知內容:</p><pre class="brush:js;toolbar:false">{
"aps": {
"alert": {
"title":"Hello! :)",
"body":"App closed..."
},
"badge":1,
"sound":"default"
}
}</pre><p><strong>應用程序的生命週期</strong></p><p>拷貝device token粘貼在Pusher的token部分,拷貝這個JSON對象在Pusherd的payload部分。</p><p style="text-align:center"><img src="http://cc.cocimg.com/api/uploads/20160803/1470204340320844.png" title="1470204340320844.png" alt="QQ截圖20160803140530.png"></p><p>試着發送第一個通知。如果設備的屏幕被鎖定,它將看起來如下,但什麼都不會發生,當用戶點擊了這個通知視圖。</p><p style="text-align:center"><img src="http://cc.cocimg.com/api/uploads/20160803/1470204366816796.jpg" title="1470204366816796.jpg" alt="ios10_notifications_-translate_13.jpg"></p><p>接受通知,你需要添加新的方法:</p><pre class="brush:js;toolbar:false">private func getAlert(notification: [NSObject:AnyObject]) -> (String, String) {
let aps = notification["aps"] as? [String:AnyObject]
let alert = aps?["alert"] as? [String:AnyObject]
let title = alert?["title"] as? String
let body = alert?["body"] as? String
return (title ?? "-", body ?? "-")
}</pre><p>這將返回收到的通知標題和正文,如果結構是相同的。</p><pre class="brush:js;toolbar:false">func notificationReceived(notification: [NSObject:AnyObject]) {
let viewController = window?.rootViewController
let view = viewController as? ViewController
view?.addNotification(
title: getAlert(notification: notification).0,
body: getAlert(notification: notification).1)
}</pre><p>這個方法將在應用程序主要視圖UITableView內添加一行(參見ViewController的完整項目代碼)。</p><p>我測試了三個案例的推送通知:</p><ul class=" list-paddingleft-2"><li><p><strong>當應用關閉時</strong></p></li></ul><p>如果用戶打開應用程序的通知,調用didFinishLaunchingWithOptions方法更新,如下:</p><pre class="brush:js;toolbar:false">func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.applicationIconBadgeNumber = 0; // Clear badge when app launches
// Check if launched from notification
if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
window?.rootViewController?.present(ViewController(), animated: true, completion: nil)
notificationReceived(notification: notification)
} else {
registerPushNotifications()
}
return true
}</pre><p>假設用戶已經看過了這個通知,那麼角標就被清除了。然後,檢查應用程序是從圖標打開還是通過通知打開的。在第一種情況下,調用registerPushNotifications()方法然後繼續之前的流程。如果應用是通過打開通知的方式運行,則調用自定義notificationReceived方法來添加行。</p><ul class=" list-paddingleft-2"><li><p><strong>當應用運行在前臺時</strong></p></li></ul><p>如果用戶正在使用應用程序,這意味着應用程序在前臺,接受通知的方法如下。在這個通知的方法中加入對tableView的處理:</p><pre class="brush:js;toolbar:false">func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
notificationReceived(notification: userInfo)
}</pre><p>注意:在這種情況下,通知將不會發出聲音。</p><ul class=" list-paddingleft-2"><li><p><strong>當應用運行在後臺時</strong></p></li></ul><p>在這種情況下,我添加了一個方法來清除角標數目。通知的處理和應用程序在前臺的處理是一樣的。</p><pre class="brush:js;toolbar:false">func applicationWillEnterForeground(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0; // Clear badge when app is or resumed
}</pre><p>最後,這個列表中有三行來自通知的內容。</p><p style="text-align:center"><img src="http://cc.cocimg.com/api/uploads/20160803/1470204437895414.jpg" title="1470204437895414.jpg" alt="1468368533IMG_7507.jpg"></p><p><strong>最後</strong></p><p>隨着iOS 10的通知,開發者有了更多比之前有趣的機會和不曾有的交互權限。我希望本教程中關於如何使用通知能幫助你更好的理解通知是如何工作的。</p>
</devicetoken.count {>