Firebase推播(下) - 图片推播

缘由:

推播时带图片是很常见的,只是没想到当时我搞了好几天,查到的资料零零落落,有些教程会让人在走偏的道路上越走越偏/images/emoticon/emoticon10.gif,後来才知道原来需要扩展推播的功能,才能在推播上显示图片,且这样就得另创target,意味着会再创一个id,因为是扩展app的推播功能,所以创建新target时配好的id会长的像这样
原target的id:com.test.abc
NotificationServiceExtension的id:com.test.abc.[target名称]
然後因为扩展推播的功能也会使用到Firebase,所以需要至Podfiles中去新增新target要安装的套件,
接着再回来新target项下新创建的NotificationService.swift,导入Firebase函式库,在didReceive里添加我们要使用的firebase扩展功能~

实作:

Step 1:
在Project Navigator中,点击红匡位置的“+”来新增新的target
https://ithelp.ithome.com.tw/upload/images/20210924/20130757Ir9WGGhjbk.png
在弹出的target类型视窗中,选择“Notification Service Extension”
https://ithelp.ithome.com.tw/upload/images/20210924/201307573fLVT3XWsH.png
然後按照步骤即可完成创建

Step 2:
到APPLE开发者後台,用此新的App id建立新的Provisioning Profile,下载後於Singing中选用
https://ithelp.ithome.com.tw/upload/images/20210924/20130757Szajw4SI0j.png
https://ithelp.ithome.com.tw/upload/images/20210924/20130757CybDbY2hu7.png
https://ithelp.ithome.com.tw/upload/images/20210924/20130757B7veW2z5LY.png
https://ithelp.ithome.com.tw/upload/images/20210924/20130757QsuH981d1c.png

Step 3:
重新安装第三方套件,开启终端机移动目前的位置至专案资料夹,然後用vim 编辑器开启Podfiles
下方的'RemotePush’target是原本的APP target,而'NotificationServiceExt’target是我後来加上的部分

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'RemotePush' do
  # Comment the next line if you don't want to use dynamic frameworks
  pod 'Firebase/Analytics'
  pod 'Firebase/Core'
  pod 'Firebase/Messaging'
  use_frameworks!

  # Pods for RemotePush
target 'NotificationServiceExt' do
    inherit! :search_paths
end


end

以上编辑完後储存离开,然後执行pod install,这阶段就算结束了

Step 4:
在新创建的target项下,寻找NotificationService.swift档案,导入函式库import Firebase,然後在override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)中添加下面这段

    if bestAttemptContent != nil {
        return FIRMessagingExtensionHelper().populateNotificationContent(
        bestAttemptContent!,
        withContentHandler: contentHandler)
    }

若你要修改传送来的标题或内容,也可以另外将bestAttemptContent拉出来指定title和body即可
然後将App安装到实机,可以开始测试了

Step 5:
至Firebase 专案後台的Cloud Messaging中建立新通知(图片我是存在firebase的storage中)
https://ithelp.ithome.com.tw/upload/images/20210924/20130757PJVv0rMi6O.png
接着等候推播
下方为图片推播成功的画面
https://ithelp.ithome.com.tw/upload/images/20210924/20130757FnSrRfH51N.png
https://ithelp.ithome.com.tw/upload/images/20210924/20130757ZaqKWrJ8Nb.png


<<:  Youtube Data API 教学 - 有字幕好安心 Captions.list

>>:  [Day09] while、for 回圈

[Day - 17 ] - Spring 导入选择器原理与开发

Abstract 我们前面已经讨论了相当多种取得Bean的方法,如:自动注入(@Autowired、...

AI ninja project [day 30] 结语

以前我与一群在当医检师的同学聚餐的时候, 我说了我在写 Python, 而他们却问说那是什麽? 我不...

Day8 Switch case

Switch case 是一个跟if else 相似的条件判段与陈述句,不过他只能用来比较数值或字元...

Day22 AWS - SignUp & MFA

先前开发的功能都是只有在本机执行,顶多同一个区域网路的用户可以使用服务,还是得想个办法让其他外网用户...

.Net Core Web Api_笔记11_组合路由

在一个Action中倘若想实现多种结果返回或者多种输入参数 就势必要能够支援多种路由模板 可能搭配不...