Swift:如何在主项目和消息扩展之间共享动态图像

时间:2017-10-31 17:03:07

标签: ios swift image mssticker

我正在尝试为我的应用添加贴纸扩展程序,以便用户可以在我的应用中创建贴纸,然后在消息中使用它们。但是,文件路径似乎不同,所以我无法将图像保存到文件路径,然后将它们加载到消息扩展中。 基本上,在应用程序及其扩展程序之间共享数据的最佳方式是什么?特别是对于NSUserDefaults来说太大的数据。

2 个答案:

答案 0 :(得分:0)

我找到了答案,将目标放在一个组中,您可以访问相同的fileManager路径

答案 1 :(得分:0)

如果要在主项目和应用扩展程序之间共享数据,则必须启用AppGroups

可以在此处找到启用和共享数据的整个教程(http://www.theappguruz.com/blog/ios8-app-groups)。

启用AppGroups后,您可以将创建的贴纸存储在共享容器中,如下所示:

if let fileManager = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "") 
{
     let imageName = "imageName" // write your image name here
     let imageLocationUrl = fileManager.appendingPathComponent(imageName)

     // for saving image

     if let data:Data = UIImagePNGRepresentation(image) {
         do {
            try data.write(to: imageLocationUrl)
         }catch {
                // couldn't write
         }
     }
}

获取图像,

if let fileManager = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "") 
{
     let imageName = "imageName" // write your image name here
     let imageLocationUrl = fileManager.appendingPathComponent(imageName)

     // for getting image

     if let data:Data = Data(contentsOfFile: imageLocationUrl.path) {
        let image = UIImage(data: data, scale: UIScreen.main.scale)
     }
}