Ios 应用程序扩展名如何访问包含应用程序文档/文件夹的文件

Ios 应用程序扩展名如何访问包含应用程序文档/文件夹的文件,ios,filesystems,ios-app-extension,Ios,Filesystems,Ios App Extension,在应用程序扩展中,是否有方法获取从存储在/var/mobile/Containers/Data/Application//Documents//文件夹中的包含应用程序生成的图像 为了使文件可供应用程序扩展名使用,您必须使用组路径,因为应用程序扩展名无法访问应用程序的文档文件夹,为此,您必须遵循以下步骤 从项目设置->功能中启用应用程序组 添加组扩展名,例如group.yourappid 然后使用下面的代码 NSString *docPath=[self groupPath]; NSArray

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

为了使文件可供应用程序扩展名使用,您必须使用
组路径
,因为应用程序扩展名无法访问应用程序的文档文件夹,为此,您必须遵循以下步骤

  • 项目设置->功能中启用应用程序组
  • 添加组扩展名,例如
    group.yourappid
  • 然后使用下面的代码

    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;
    }
    
  • 您可以根据正在生成的图像扩展名添加或更改路径扩展名

    注意-请记住,您需要在group文件夹而不是Documents文件夹中生成图像,这样应用程序和分机都可以使用这些图像。

    干杯

    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/folder.hi@iphone你对这个问题有何想法我想在extensions项目中写入日志,我已经在app group共享文件夹中创建了文件,但它仍然无法在文件中写入数据,你知道为什么吗?