首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UNNotificationServiceExtension中无效的附件文件URL

UNNotificationServiceExtension中无效的附件文件URL
EN

Stack Overflow用户
提问于 2017-12-23 04:52:10
回答 1查看 978关注 0票数 0

我编写了一个UNNotificationServiceExtension,在这里我试图下载一个文件并附加它。每次我跑的时候都会有个例外说

附件文件URL无效。

我一辈子都搞不懂为什么会失败。

代码语言:javascript
复制
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    let bestAttemptContent = request.content.mutableCopy() as! UNMutableNotificationContent

    guard let urlPath = request.content.userInfo["media-url"] as? String,
        let url = URL(string: urlPath) else {
            contentHandler(bestAttemptContent)
            return
    }

    let semaphore = DispatchSemaphore(value: 0)

    URLSession.shared.downloadTask(with: url) {
        location, _, _ in

        defer { semaphore.signal() }

        guard let location = location else { return }

        var destination: URL!

        do {
            destination = try FileManager.default.url(for: .itemReplacementDirectory,
                                                      in: .userDomainMask,
                                                      appropriateFor: location,
                                                      create: true)
            destination.appendPathComponent(url.lastPathComponent)
            let attachment = try UNNotificationAttachment(identifier: "",
                                                          url: destination)
            bestAttemptContent.attachments = [attachment]
        } catch let error {
            bestAttemptContent.body = error.localizedDescription + "\n" + destination.absoluteString
        }
    }.resume()

    _ = semaphore.wait(timeout: .distantFuture)

    contentHandler(bestAttemptContent)
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-05 09:39:54

如果你还在找代码,就在这里,

代码语言:javascript
复制
class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        func failEarly() {
            contentHandler(request.content)
        }

        guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
            return failEarly()

        }
        guard let apnsData = content.userInfo["data"] as? [String: Any] else {
            return failEarly()

        }

        guard let attachmentURL = apnsData["media-url"] as? String else {
            return failEarly()

        }

        guard let imageData = NSData(contentsOf:NSURL(string: attachmentURL)! as URL) else {
            return failEarly()

        }

        bestAttemptContent?.attachments = [create(imageFileIdentifier: "image.jpg", data: imageData, options: nil)!]
        contentHandler(bestAttemptContent!)

    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}

func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {

    let tmpSubFolderName: String = ProcessInfo.processInfo.globallyUniqueString
    let fileURLPath: String = NSTemporaryDirectory()
    let tmpSubFolderURL: String = URL(fileURLWithPath: fileURLPath).appendingPathComponent(tmpSubFolderName).absoluteString

    if ((try? FileManager.default.createDirectory(atPath: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)) != nil) {
        let fileURL = URL(fileURLWithPath: tmpSubFolderURL).appendingPathComponent(imageFileIdentifier)
        data.write(to: fileURL, atomically: true)
        let attachment = try? UNNotificationAttachment(identifier: imageFileIdentifier, url: fileURL, options: options)
        return attachment!
    }
    return nil

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47949857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档