今天我們要練習的是如何使用推播功能,主要參考ref6的文章來實作。
守護石虎,人人有責
現在,我們馬上開始!
建立專案請參考 Day13
https://ithelp.ithome.com.tw/articles/10221914
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound,
.badge]) { (granted, error) in
if granted {
print("使用者同意接收推播通知")
}
}
return true
}
options內可以設定多種推播的格式(警示,聲音...)
granted 使用者是否同意接收推播 (Allow)
@IBAction func catButtonPressed(_ sender: UIButton) {
let content = UNMutableNotificationContent()
content.title = "守護石虎人人有責"
content.subtitle = "石虎抱抱"
content.body = """
向親朋好友介紹石虎,讓他們更喜愛這種動物
向親朋好友介紹石虎面臨的困境
行車時若看見小心石虎的標誌請減速慢行
(苗栗縣相關標誌類似附圖)
不使用捕獸鋏、避免使用農藥和有毒餌劑
不任意棄養寵物、不任意獵殺野生動物
"""
content.badge = 3
content.sound = UNNotificationSound.default
let imageURL = Bundle.main.url(forResource: "Cat2", withExtension: "jpg")
let attchment = try! UNNotificationAttachment(identifier: "catNotification1", url: imageURL!, options: nil)
content.attachments = [attchment]
// time interval must be at least 60 if repeating
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "notification1", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
『content.sound』 提示音效
『badge』 為桌面上App顯示的數字
『content.attachments』 推播的附件,可放圖片,音樂...
『UNNotificationRequest(identifier: "notification1"』
發出請求的request,並設定識別ID為notification1
『UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)』
=> 觸發時間5秒不重複,如果重複時間不可低於60秒
推播內容對照圖
// remove pending notifications (尚未收到的推播)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification1"])
// remove all pending notifications
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
// Removes the specified notification requests from Notification Center. (收到尚未開啟)
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notification1"])
// Removes all of the app’s delivered notifications from Notification Center.
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 前景通知
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if let error = error {
print(error)
return
}
// UIApplicationEndBackgroundTaskError()
if granted {
print("使用者同意接收推播通知")
}
}
return true
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .sound, .alert])
}
}
此時我們測試此功能可以運作,但會產生如下錯誤
除錯過程: 參考本文的『Symbolic Breakpoint』,但是並沒發現錯誤的原因
再次網路爬文找到解答(ref10),iOS12.4之後都會有此錯誤警告訊息,但是功能可正常運作
// send request right now
//let request2 = UNNotificationRequest(identifier: "notification1", content: content, trigger: nil)
可以看到錯誤訊息
在今天的文章裡,我們練習了如何使用推播功能,除了文字訊息以外,還可以加入圖片,提示音效等等。
過程中發現有個iOS13 (after iOS 12.4)無法排除的警告訊息,目前在Apple開發者論壇也還沒有解答,先做個紀錄。而明天的文章將會繼續實作客製化的通知。
今天的內容就到這邊,感謝讀者們的閱讀。
https://github.com/chiron-wang/IT30_11
彼得潘的 Swift iOS App 開發問題解答集
https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86
iOS 13 & Swift 5 - The Complete iOS App Development Bootcamp - Angela Yu
https://www.udemy.com/course/ios-13-app-development-bootcamp/
深入淺出 iPhone 開發 (使用 Swift4) - WeiWei
https://www.udemy.com/course/iphone-swift4/
心智圖軟體Xmind
https://www.xmind.net/
俄羅斯插畫家親繪石虎送台灣 有望登上彩繪列車!
https://udn.com/news/story/7266/4013861
結合 iOS 10 的 User Notifications:傳送米花兒的幸福打氣通知
https://www.appcoda.com.tw/ios10-user-notifications/
apple dev doc notification center
https://developer.apple.com/documentation/usernotifications/unusernotificationcenter
Break in UIApplicationEndBackgroundTaskError() to debug
https://forums.developer.apple.com/thread/22836
UNUserNotificationCenter did receive response with completion handler is never called iOS10, swift 2.3
https://stackoverflow.com/questions/38954496/unusernotificationcenter-did-receive-response-with-completion-handler-is-never-c
"Can't end BackgroundTask" error message on iOS 13.0
https://forums.developer.apple.com/thread/121990
Sending Notification Requests to APNs
https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns