如何从UNNotificationContentExtension安排本地通知时获取访问附件

时间:2019-12-13 05:01:41

标签: ios swift notifications uilocalnotification unnotificationscontentextension

我正在开发一种功能,用户可以在x分钟后重新安排通知及其附件。我正在安排notification extension中的通知,并在内容上进行一些细微更改(以删除schedule later UNNotificationAction按钮),并使用未更改的内容附件来安排

//get bestAttemtContent from `didReceive(_ notification: UNNotification)` on showing custom view of notification 
let request = UNNotificationRequest(identifier: identifier,
                                        content: bestAttemptContent,
                                        trigger: trigger)
UNUserNotificationCenter.current()..add(request) { _ in

       } 

在设备上收到通知后的x分钟后,我无法访问该网址(有时会随机解析书签)

if bestAttemptContent.attachments[0]
            .url.startAccessingSecurityScopedResource()  { // This return false sometimes randomly when called second time by local schedule push
  // access image attachment to show in the view 
}

-尝试的方法

在NSTemporaryDirectory中写入数据,但是我也无法访问,似乎扩展名终止时数据已清除

    func copyAtNewLocation() throws -> UNNotificationAttachment? {
        defer {
            url.stopAccessingSecurityScopedResource()
        }

        let fileManager = FileManager.default
        let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
        let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory())
            .appendingPathComponent(tmpSubFolderName, isDirectory: true)
        do {
            try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
            let fileURL = tmpSubFolderURL.appendingPathComponent(url.lastPathComponent)
            if url.startAccessingSecurityScopedResource() {
                if let data = try? Data(contentsOf: url) {
                    // Access Data written in previous location
                    try data.write(to: fileURL, options: [])
                    UserDefaults.standard.set(fileURL, forKey: "lastAttachmentURL")
                    let newAttachment = try UNNotificationAttachment(identifier: UUID().uuidString, url: fileURL, options: [:])
                    return newAttachment
                }
            }
        }
        return nil
    }
}

After schedule local notification From remote push notification with remainder action button

link已经消失了,请不要将其标记为重复

0 个答案:

没有答案
相关问题