![](/img/trans.png)
[英]Cannot attach media in remote notification using notification service extension in ios 10
[英]iOS 10 Notification Content Extension: using NSURLSession?
我正在嘗試在 iOS 10 中為本地通知創建一個新的通知內容擴展,其中負責內容擴展的通知視圖控制器從網絡下載圖像並將其呈現在 UIImageView 中。 我使用適當的 Info.plist 設置了通知內容擴展目標,內容擴展非常適合簡單的事情,例如渲染帶有某些內容的標簽,例如模板中的示例代碼:
func didReceive(_ notification: UNNotification) {
self.label.text = notification.request.content.body
}
但是,當我嘗試將 NSURLSession(或 Swift 3 中的 URLSession)引入混合時,通知內容完全無法加載 - 甚至不再設置標簽:
func didReceive(_ notification: UNNotification) {
self.label.text = notification.request.content.body
let session = URLSession.shared()
let url = URL(string: "https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World")!
let task = session.downloadTask(with: url) { (fileURL, response, error) in
if let path = fileURL?.path {
DispatchQueue.main.async {
self.imageView.image = UIImage(contentsOfFile:path)
}
}
}
task.resume()
}
是否不允許在通知內容擴展中使用 NSURLSession? 我的擴展程序是否可能在下載完成之前被殺死? 如果是這樣,我如何確保它沒有被殺死,以便我可以下載和渲染圖像?
在內容擴展中調用func didReceive(_ notification: UNNotification)
,對內容的任何修改(例如下載圖像)都應該已經發生。
您似乎使用通知服務擴展來下載任何其他內容。 如果您需要,通知內容擴展僅負責提供自定義用戶界面。
在您的服務擴展中,您使用通知負載中的 url 下載圖像,並將其設置為UNNotification
對象上的附件。 如果您不需要任何自定義 UI,系統將自動顯示視頻或圖像等視覺媒體附件。 如果這滿足您的需求,您實際上根本不需要通知內容擴展。
推桿提供有關設置通知服務擴展iOS上的10中處理媒體附件在推送通知一個偉大的教程在這里。
實際上可以在Notification Content Extension
下載圖像。 但是,您的代碼包含兩個問題:
downloadTask
方法返回的fileURL
一旦函數運行超出范圍就會被刪除,當您嘗試從另一個線程訪問fileURL
時已經是這種情況。 相反,最好在數據變量中捕獲fileURL
內容並使用它在fileURL
成圖像稍微更正的代碼:
guard let url = URL(string: "https://betamagic.nl/images/coredatalab_hero_01.jpg") else {
return
}
let task = URLSession.shared.downloadTask(with: url) { (fileURL, response, error) in
if let fileURL = fileURL,
let data = try? Data(contentsOf: fileURL) {
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data)
}
}
}
task.resume()
在 Info.plist 中為您的擴展禁用應用傳輸安全。 提示:將文件從 tmp 文件夾移動到緩存以進行保存
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.