原文鏈接
作者:Arthur Knopper
原文日期:2016-10-11
譯者:Crystal Sun
本地通知(Local Notification)可以在用戶沒有使用某 App 的時候將消息推送給用戶。iOS 10 里蘋果公司介紹了非常多的通知,設置包含不同類型的通知。在本節教程中,我們將創建一個本地通知,可以推送圖片消息。本節教程使用的是 Xcode 8 和 iOS 10。
打開 Xcode,創建一個 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 類里,創建下圖 Action。
找到 ViewController.swift 文件,更改 viewDidLoad 方法如下:
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { (success, error) in
if success {
print("success")
} else {
print("error")
}
}
}
UNUserNotificationCenter 管理與通知相關的行為,想要使用通知,必須先獲取用戶的同意,可使用 requestAuthorization 方法。
我們將一張圖片作為通知的附件。下載圖片,將其引入工程。接下來實現 sendNotification
方法。
@IBAction func sendNotification(_ sender: AnyObject) {
// 1
let content = UNMutableNotificationContent()
content.title = "Notification Tutorial"
content.subtitle = "from ioscreator.com"
content.body = " Notification triggered"
// 2
let imageName = "applelogo"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
// 3
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "notification.id.01", content: content, trigger: trigger)
// 4
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
- UNMutableNotificationContent 對象包含通知的數據。
- UNNotificationAttachment 對象包含通知的媒體內容。
- UNNotificationRequest 被創建成功,將會在 10 秒內被觸發。
- 安排傳遞通知。
運行工程,首先獲取用戶的同意。
點擊 Allow,然后點擊 “Send Local Notification”按鈕來安排通知,接著點擊模擬器 Home 鍵(Shift + Command + H)回到屏幕主頁。十秒之后接收到了本地通知。
在 ioscreator 的 github 上可以下載到本節課程 IOS10LocalNotificaitonTutorial 的源代碼。
本文由 SwiftGG 翻譯組翻譯,已經獲得作者翻譯授權。