iOS 10 之前用戶通知相對而言是簡單的懂讯,iOS 10讓用戶通知更加豐富了荷憋,可以有靜態(tài)圖片,動態(tài)gif褐望,視頻勒庄,音頻等。
用戶通知可以出現(xiàn)在通知中心瘫里,主屏实蔽,鎖屏時,當用戶錯過了用戶通知時减宣,可以在通知中心查看盐须。
用戶通知分為兩類:
- 本地通知。 是通過應用本身和用戶設備本身觸發(fā)的漆腌。比如:基于用戶位置的app贼邓,在用戶進入某個特殊區(qū)域發(fā)送通知;to-do list的app在某些特定時間發(fā)送通知闷尿。
- 遠程通知塑径。 是遠程服務器端首先向蘋果推送服務器(Apple Push Notification Service ,APNS)發(fā)送填具,然后再經(jīng)過APNS推送通知到用戶設備统舀。
這一篇只討論本地通知。
三種不同觸發(fā)的本地通知:
- 特定數(shù)量的時間劳景。 比如是10分鐘后誉简。
- 特定日期和時間點。
- 特定位置盟广。
詢問用戶授權
向用戶發(fā)送通知是要得到用戶允許的闷串。
- 在
AppDelegate.swift
中添加import UserNotifications
- 在
application(_:didFinishLaunchingWithOptions:)
方法中添加授權UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { (granted, error) in if granted { print("User notifications are allowed.") } else { print("User notifications are not allowed.") } })
創(chuàng)建通知
通知的一般結(jié)構(gòu):
通知用UNMutableNotificationContent
類來表示。
- 在
RestaurantTableViewController
中添加一個方法
func prepareNotification() {
// Make sure the restaurant array is not empty
if restaurants.count <= 0 {
return
}
// 1
let randomNum = Int(arc4random_uniform(UInt32(restaurants.count)))
let suggestedRestaurant = restaurants[randomNum]
// 2
let content = UNMutableNotificationContent()
content.title = "Restaurant Recommendation"
content.subtitle = "Try new food today"
content.body = "I recommend you to check out \(suggestedRestaurant.name!).The restaurant is one of your favorites. It is located at \(suggestedRestaurant.location!). Would you like to give it a try?"
content.sound = UNNotificationSound.default()
// 3
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats:
false)
let request = UNNotificationRequest(identifier: "foodpin.restaurantSuggestion", content: content, trigger: trigger)
// Schedule the notification
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
- 1 獲得一個隨機的restaurant
- 2 通過
UNMutableNotificationContent
獲得一個通知筋量,配置參數(shù)烹吵,sound
表示需要通知聲音。 - 3
UNTimeIntervalNotificationTrigger
是一個時間觸發(fā)桨武,為了好測試肋拔,表示10s后通知一次。
- 在
viewDidLoad
中實現(xiàn)上面函數(shù)呀酸。prepareNotification()
現(xiàn)在運行凉蜂,注意在應用內(nèi)是不能接受本應用通知,所以運行后立即進入主屏或鎖屏性誉。通知本身有高度限制窿吩,內(nèi)容過長會不顯示,只要向下滑動就可以顯示完整艾栋。
向通知中添加圖片
圖片等富文本內(nèi)容通過UNMutableNotificationContent
的attachments
屬性添加爆存,attachments
屬性是UNNotificationAttachment
的數(shù)組。UNNotificationAttachment
可以是圖片蝗砾、音頻先较、音效、視頻文件悼粮。
- 在
prepareNotification
中的觸發(fā)之前添加代碼:// 1 let tempDirURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let tempFileURL = tempDirURL.appendingPathComponent("suggested-restaurant.jpg") if let image = UIImage(data: suggestedRestaurant.image! as Data) { // 2 try? UIImageJPEGRepresentation(image, 1.0)?.write(to: tempFileURL) if let restaurantImage = try? UNNotificationAttachment(identifier: "restaurantImage", url: tempFileURL, options: nil) { content.attachments = [restaurantImage] } }
- 1 由于使用Core Data闲勺,圖片以
NSData
形式存儲了,所以使用NSTemporaryDirectory
來生成臨時目錄存儲臨時圖片文件 - 2
UIImageJPEGRepresentation
用來生成jpg圖片文件
- 1 由于使用Core Data闲勺,圖片以
運行查看扣猫,同樣向下滑動可查看完整菜循。
和通知的交互
之前只要點擊通知進入應用的交互,這是默認的交互申尤。
- 在
prepareNotification
中的觸發(fā)之前添加代碼:// 1 let categoryIdentifer = "foodpin.restaurantaction" // 3 let makeReservationAction = UNNotificationAction(identifier: "foodpin.makeReservation", title: "Reserve a table", options: [.foreground]) let cancelAction = UNNotificationAction(identifier: "foodpin.cancel", title: "Later", options: []) // 4 let category = UNNotificationCategory(identifier: categoryIdentifer, actions:[makeReservationAction, cancelAction], intentIdentifiers: [], options: []) // 5 UNUserNotificationCenter.current().setNotificationCategories([category]) // 2 content.categoryIdentifier = categoryIdentifer
- 1,2
categoryIdentifier
是讓通知和category關聯(lián)起來 - 3
UNNotificationAction
有點類似UIAlertAction
癌幕,options: [.foreground]
表示讓應用到前臺衙耕,就是啟動應用 - 4
UNNotificationCategory
有點類似UIAlertController
- 5 把
UNNotificationCategory
注冊到用戶中心
- 1,2
處理Actions
上面的options: [.foreground]
只是啟動了應用,沒有實現(xiàn)具體操作勺远。UNUserNotificationCenterDelegate
中的userNotificationCenter(_:didReceive:withCompletionHandler:)
方法在UNNotificationAction
被選擇時調(diào)用橙喘,在這個方法內(nèi)部可實現(xiàn)具體操作。
- 讓
AppDelegate
符合協(xié)議UNUserNotificationCenterDelegate
- 實現(xiàn)
userNotificationCenter(_:didReceive:withCompletionHandler:)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 1 if response.actionIdentifier == "foodpin.makeReservation" { print("Make reservation...") // 2 if let phone = response.notification.request.content.userInfo["phone"] { let telURL = "tel://\(phone)" if let url = URL(string: telURL) { if UIApplication.shared.canOpenURL(url) { print("calling \(telURL)") // 3 UIApplication.shared.open(url) } } } } completionHandler() }
- 1 對應之前創(chuàng)建
UNNotificationAction
時的identifier
胶逢。 - 2
response.notification.request.content
對應之前創(chuàng)建通知prepareNotification
函數(shù)中的UNMutableNotificationContent
厅瞎,userInfo
屬性可用來存儲通知想傳遞的數(shù)據(jù)。比如在prepareNotification
函數(shù)中添加content.userInfo = ["phone": suggestedRestaurant.phone!]
初坠,這邊就可獲得和簸。 - 3 撥打電話。
- 1 對應之前創(chuàng)建
- 在
content.userInfo = ["phone": suggestedRestaurant.phone!]
中添加UNUserNotificationCenter.current().delegate = self
碟刺。
代碼
Beginning-iOS-Programming-with-Swift
說明
此文是學習appcode網(wǎng)站出的一本書 《Beginning iOS 10 Programming with Swift》 的一篇記錄
目錄
- 開始用Swift開發(fā)iOS 10 - 1 前言和目錄
- 開始用Swift開發(fā)iOS 10 - 2 Hello World锁保!第一個Swift APP
- 開始用Swift開發(fā)iOS 10 - 3 介紹Auto Layout
- 開始用Swift開發(fā)iOS 10 - 4 用Stack View設計UI
- 開始用Swift開發(fā)iOS 10 - 5 原型的介紹
- 開始用Swift開發(fā)iOS 10 - 6 創(chuàng)建簡單的Table Based App
- 開始用Swift開發(fā)iOS 10 - 7 定制Table Views
- 開始用Swift開發(fā)iOS 10 - 8 Table View和UIAlertController的交互
- 開始用Swift開發(fā)iOS 10 - 10 Navigation Controller的介紹和Segue
- 開始用Swift開發(fā)iOS 10 - 11 面向?qū)ο缶幊探榻B
- 開始用Swift開發(fā)iOS 10 - 12 豐富Detail View和定制化Navigation Bar
- 開始用Swift開發(fā)iOS 10 - 13 Self Sizing Cells and Dynamic Type
- 開始用Swift開發(fā)iOS 10 - 14 基礎動畫,模糊效果和Unwind Segue
- 開始用Swift開發(fā)iOS 10 - 15 使用地圖
- 開始用Swift開發(fā)iOS 10 - 16 介紹靜態(tài)Table Views南誊,UIImagePickerController和NSLayoutConstraint
- 開始用Swift開發(fā)iOS 10 - 17 使用Core Data
- 開始用Swift開發(fā)iOS 10 - 18 Search Bar 和 UISearchController
- 開始用Swift開發(fā)iOS 10 - 19 使用UIPageViewController構(gòu)建介紹頁面
- 開始用Swift開發(fā)iOS 10 - 20 使用Tab Bar Controller 和 拆分Storyboard
- 開始用Swift開發(fā)iOS 10 - 21 使用WKWebView和SFSafariViewController
- 開始用Swift開發(fā)iOS 10 - 22 使用CloudKit
- 開始用Swift開發(fā)iOS 10 - 24 使用TestFlight進行Beta測試
- 開始用Swift開發(fā)iOS 10 - 25 使用3D Touch
- 開始用Swift開發(fā)iOS 10 - 26 使用本地用戶通知