How can app extension access files in containing app Documents/ folder

纵饮孤独 提交于 2019-12-09 05:17:30

问题


In the app extension is there a way to get images generated from the containing app which is store in /var/mobile/Containers/Data/Application//Documents// folder?


回答1:


In order to make files available to app extension you have to use Group Path, as App Extension can't access app's Document Folder, for that you have follow these steps,

  1. Enable App Groups from Project Settings-> Capabilities.
  2. Add a group extension something like group.yourappid.
  3. Then use following code.

    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;
    }
    

You can add or change the path extension as per your image extensions you are generating.

Note - Remember you need to generate the images in the group folder rather than in Documents Folder, so it is available to both app and extension.

Cheers.

Swift 3 Update

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!)
}


来源:https://stackoverflow.com/questions/38691893/how-can-app-extension-access-files-in-containing-app-documents-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!