當(dāng)用戶沒有在前臺使用某 App 的時候疼约,通過本地通知(Local Notification)可以將消息推送給用戶。iOS 10 里蘋果公司引入了多信息通知 (rich notifications)民镜,其中可以包含不同類型的媒體內(nèi)容腰奋。我們將創(chuàng)建一個本地通知,其中包含了一個圖片消息东囚。使用的是 Xcode 8 和 iOS 10之剧。
打開 Xcode郭卫,創(chuàng)建一個 Single View Application。
點擊 Next背稼,product name 一欄填寫IOS10LocalNotificationTutorial贰军,填寫好 Organization Name 和 Organization Identifier,Language 選擇 Swift蟹肘,Devices 選擇 iPhone词疼。
找到Storyboard,拖一個 Button 控件到主視圖中帘腹,將其 title 改為 “Send Local Notification”贰盗。選中此 Button 控件,隨后點擊 Auto Layout 的 Align 按鈕阳欲,選中其中的 Horizontally in Container 選項童太,然后在 “Update Frame” 的下拉選項中選擇 “Item of New Constraints”,最后點擊 “Add 1 Constraint”胸完。
接下來,依然選中 Button 控件翘贮,點擊 Auto Layout 的 Pin 按鈕赊窥,然后點擊向上的豎線,在 “Update Frame” 的下拉選項中選擇 “Item of New Constraints”狸页,最后點擊 “Add 1 Constraint”锨能。
在這時候 Storyboard 會是下圖這個樣子:
打開 Assistant Editor扯再,確保ViewController.swift文件可見,按住 Ctrl 鍵并同時拖拽 Button 按鈕到 ViewController 類里址遇,創(chuàng)建如下圖所示的 Action熄阻。
找到ViewController.swift文件,更改viewDidLoad方法為如下所示:
overridefuncviewDidLoad(){
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { (success, error)in
ifsuccess {
print("success")
}else{
print("error")
}
}
}
UNUserNotificationCenter用以管理與通知相關(guān)的行為倔约。如果想要使用通知的話秃殉,必須先獲取用戶的授權(quán),才可使用requestAuthorization方法浸剩。
我們將一張圖片作為通知的附件钾军。從這里下載這張圖片,然后將其引入工程绢要。接下來實現(xiàn)sendNotification方法吏恭。
@IBActionfuncsendNotification(_sender: AnyObject){
// 1
letcontent =UNMutableNotificationContent()
content.title ="Notification Tutorial"
content.subtitle ="from ioscreator.com"
content.body =" Notification triggered"
// 2
letimageName ="applelogo"
guardletimageURL =Bundle.main.url(forResource: imageName, withExtension:"png")else{return}
letattachment =try!UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
// 3
lettrigger =UNTimeIntervalNotificationTrigger(timeInterval:10, repeats:false)
letrequest =UNNotificationRequest(identifier:"notification.id.01", content: content, trigger: trigger)
// 4
UNUserNotificationCenter.current().add(request, withCompletionHandler:nil)
}
UNMutableNotificationContent對象包含有通知當(dāng)中的數(shù)據(jù)。
UNNotificationAttachment對象包含有通知當(dāng)中的媒體內(nèi)容重罪。
UNNotificationRequest被創(chuàng)建成功后樱哼,將會在 10 秒內(nèi)被觸發(fā)。
系統(tǒng)將會安排通知的傳遞剿配。
編譯并運(yùn)行工程搅幅。這個時候會申請用戶的授權(quán)。
點擊 Allow惨篱,然后點擊 “Send Local Notification”按鈕來安排通知盏筐,接著點擊模擬器 Home 鍵(Shift + Command + H)回到屏幕主頁。十秒之后接收到了本地通知砸讳。