应用程序扩展如何访问包含在应用程序文档文件夹中的文件?

20

在应用程序扩展中,是否有一种方法可以获取从包含应用程序生成的图像,存储在 /var/mobile/Containers/Data/Application//Documents// 文件夹中?

1个回答

29

为了让文件对应用程序扩展可用,您必须使用 组路径,因为应用程序扩展无法访问应用程序的文档文件夹,为此,您必须按照以下步骤操作:

  1. 项目设置->功能中启用应用程序组
  2. 添加一个组扩展,类似于 group.yourappid
  3. 然后使用以下代码。

    NSString *docPath=[self groupPath];
    
    NSArray *contents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:docPath error:nil];
    
    NSMutableArray *images=[[NSMutableArray alloc] init];
    
        for(NSString *file in contents){
            if([[file pathExtension] isEqualToString:@"png"]){
                [images addObject:[docPath stringByAppendingPathComponent:file]];
            }
        }
    
    
    -(NSString *)groupPath{
         NSString *appGroupDirectoryPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:group.yourappid].path;
    
        return appGroupDirectoryPath;
    }
    

您可以根据要生成的图像扩展名添加或更改路径扩展名。

注意 - 记住,您需要在组文件夹中生成图像,而不是在“文档”文件夹中生成图像,以便应用程序和扩展程序都可以使用。

干杯。

Swift 3 更新

let fileManager = FileManager.default
let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "YOUR_GROUP_ID")?.appendingPathComponent("logo.png")

// Write to Group Container            
if !fileManager.fileExists(atPath: url.path) {

    let image = UIImage(named: "name")
    let imageData = UIImagePNGRepresentation(image!)
    fileManager.createFile(atPath: url.path as String, contents: imageData, attributes: nil)
}

// Read from Group Container - (PushNotification attachment example)              
// Add the attachment from group directory to the notification content                    
if let attachment = try? UNNotificationAttachment(identifier: "", url: url!) {

    bestAttemptContent.attachments = [attachment]

    // Serve the notification content
    self.contentHandler!(self.bestAttemptContent!)
}

非常感谢,这完全有效!现在我需要将所有图像转移到AppGroup//Documents/文件夹。 - Paul Smith
嗨 @iphonic,你对这个问题有任何想法吗?https://dev59.com/y7Pma4cB1Zd3GeqPkhBT?noredirect=1#comment97797926_55547930 - ikbal
我想在扩展项目中编写日志,我已经在应用程序组共享文件夹中创建了文件,但仍无法将数据写入文件,你知道为什么吗? - Anita Nagori
@Anita,你找到在扩展中登录共享容器的解决方案了吗? - Mehmet Baykar
是的,我们无法访问应用程序访问文件的文档文件夹,在应用程序和扩展中,您需要使用共享文件夹。请查看:https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html - Anita Nagori

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,