Search code examples
iosfilesystemsios-app-extension

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


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?


Solution

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