iT邦幫忙

第 11 屆 iThome 鐵人賽

1
Software Development

iOS App 實作開發新手村系列 第 31

Day31 石虎的推播通知

20191017

前言

今天我們要練習的是如何使用推播功能,主要參考ref6的文章來實作。

守護石虎,人人有責

現在,我們馬上開始!

練習過程

  1. 建立一個新專案『CatNotifications』

建立專案請參考 Day13
https://ithelp.ithome.com.tw/articles/10221914

  1. 修改AppDelegate.swift
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)

  1. 在storyboard 加入對應的UI元件 (UIImage, UIButton),並加入按鈕點擊事件

  1. 在按鈕事件加入以下代碼
@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秒

  • 推播內容對照圖

  1. 如果要取消推播通知,參考以下代碼
// 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()
  1. 加入前台推播功能,修改『AppDelegate.swift』
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
}
  1. 並在『AppDelegate.swift』最下方加入以下代碼
extension AppDelegate: UNUserNotificationCenterDelegate {
 
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.badge, .sound, .alert])
    }
}
  1. 此時我們測試此功能可以運作,但會產生如下錯誤

  2. 除錯過程: 參考本文的『Symbolic Breakpoint』,但是並沒發現錯誤的原因

  3. 再次網路爬文找到解答(ref10),iOS12.4之後都會有此錯誤警告訊息,但是功能可正常運作

  • 先做個紀錄,後續再來查看
  1. 要立刻發出推播通知,只要將trigger設定為nil
// send request right now
//let request2 = UNNotificationRequest(identifier: "notification1", content: content, trigger: nil)

Symbolic Breakpoint

  1. 加入『Symbolic breakpoint』

  1. 名稱填入『UIApplicationEndBackgroundTaskError()』

  1. 再次跑中斷

可以看到錯誤訊息

實機測試

  1. 點擊『接收石虎的訊息』,接者Home鍵

  1. 收到通知

  1. 由右邊往左邊滑動,並點擊檢視

  1. 預覽推播內容

  1. 點擊就會回到App內

總結

在今天的文章裡,我們練習了如何使用推播功能,除了文字訊息以外,還可以加入圖片,提示音效等等。

過程中發現有個iOS13 (after iOS 12.4)無法排除的警告訊息,目前在Apple開發者論壇也還沒有解答,先做個紀錄。而明天的文章將會繼續實作客製化的通知。

今天的內容就到這邊,感謝讀者們的閱讀。


Github:

https://github.com/chiron-wang/IT30_11

參考資料與延伸閱讀

  1. 彼得潘的 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

  2. iOS 13 & Swift 5 - The Complete iOS App Development Bootcamp - Angela Yu
    https://www.udemy.com/course/ios-13-app-development-bootcamp/

  3. 深入淺出 iPhone 開發 (使用 Swift4) - WeiWei
    https://www.udemy.com/course/iphone-swift4/

  4. 心智圖軟體Xmind
    https://www.xmind.net/

  5. 南投縣友善石虎農作促進會《石虎家族的綠保運動》
    https://bnwinfor.com/2018/04/21/%E5%8D%97%E6%8A%95%E7%B8%A3%E5%8F%8B%E5%96%84%E7%9F%B3%E8%99%8E%E8%BE%B2%E4%BD%9C%E4%BF%83%E9%80%B2%E6%9C%83%E3%80%8A%E7%9F%B3%E8%99%8E%E5%AE%B6%E6%97%8F%E7%9A%84%E7%B6%A0%E4%BF%9D%E9%81%8B%E5%8B%95/

  6. 俄羅斯插畫家親繪石虎送台灣 有望登上彩繪列車!
    https://udn.com/news/story/7266/4013861

  7. 結合 iOS 10 的 User Notifications:傳送米花兒的幸福打氣通知
    https://www.appcoda.com.tw/ios10-user-notifications/

  8. apple dev doc notification center
    https://developer.apple.com/documentation/usernotifications/unusernotificationcenter

  9. Break in UIApplicationEndBackgroundTaskError() to debug
    https://forums.developer.apple.com/thread/22836

  10. 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

  11. "Can't end BackgroundTask" error message on iOS 13.0
    https://forums.developer.apple.com/thread/121990

  12. Sending Notification Requests to APNs
    https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns


上一篇
Day30 學習資源匯總整理篇
下一篇
Day32 石虎的推播通知 (客製化版)
系列文
iOS App 實作開發新手村36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言