从通知服务扩展中共享数据

Han*_*nsS 6 notifications share push ios swift

我已将通知服务扩展和内容扩展添加到现有应用.服务扩展使用APNS推送通知中传递的URL下载视频文件.然后将其附加到通知中.内容扩展将附件URL传递给AVPlayer,因此如果用户决定查看,则视频将在通知内播放.到现在为止还挺好.现在我想保存下载的视频文件,以便在主视图中查看主视图.为此,我创建了一个应用程序组,为主要目标和内容服务扩展启用了应用程序组功能,并在功能中选择了应用程序组,两者都是.然后,我将下载的文件移动到应用程序组共享容器,而不是将文件保存到服务扩展中的临时目录:

let groupDirectoryUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.net.mydomain.myapp")!
let groupPathUrl = groupDirectoryUrl.appendingPathComponent("Library/Caches/myapp") // added this later to see if it would work from within the Caches directory
let groupPath = groupPathUrl.path

// Code snipped, creating myapp folder if it does not exist

do {
    try FileManager.default.moveItem(at: location, to: groupFileUrl) // location is the url of the downloaded file
    self.tmpLogger.addLogEntry(severity: 5, "<File copied to>: \(groupFileUrl)") // This is so I can view log entries from within my app
    if (FileManager.default.fileExists(atPath: groupFileUrl.path)) { // Temporary code to double check the file's existence
        self.tmpLogger.addLogEntry(severity: 5, "<File now exists>: " + groupFileUrl.path)
    }
} catch let error {
    bestAttemptContent.title = "\(bestAttemptContent.title) <FILE MOVE ERR>" // So the error will be visible in the notification, for debug
    bestAttemptContent.body = "\(bestAttemptContent.body) \(error.localizedDescription)"
    self.tmpLogger.addLogEntry(severity: 1, "<File move error>: \(error.localizedDescription)")
}
Run Code Online (Sandbox Code Playgroud)

这里没问题,移动文件有效.但是这就是主要应用程序无法看到的.在表视图控制器中:

let documentDirectoryUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.net.mydomain.myapp")!
let fileNameOnly = NSString(string: mediaEntry.fileName!).lastPathComponent //mediaEntry is CoreData, containing the url of the saved file. CoreData works
let storagePathUrl = documentDirectoryUrl.appendingPathComponent("Library/Caches/myapp")

let fileName = storagePathUrl.absoluteString.appending(fileNameOnly)
let url = URL(string: fileName)!

MyLogger().addLogEntry(severity: 5, "Filename: " + url.path)
if (FileManager.default.fileExists(atPath: url.path)) {
    // This part of the code is never reached, the file never exists
Run Code Online (Sandbox Code Playgroud)

我已更新表视图代码以重新下载视频文件(如果共享容器中不存在),并将其存储在同一位置.现在,从主应用程序开始,当选择视频事件时,视频将被下载并保存到共享容器中,然后可以查看.这将持续存在,因此可以多次查看,但只会下载一次.

我已经输入了一些代码来显示通知内容扩展中的内容.在主应用程序中下载的文件在扩展程序中不可见.因此,虽然访问共享容器时没有错误,但这两个程序无法查看彼此的数据.

我知道至少有一个应用程序扩展不允许访问共享数据,但没有找到通知服务的情况.有什么想法吗?