【问题标题】:How can app extension access files in containing app Documents/ folder应用程序扩展如何访问包含应用程序 Documents/ 文件夹中的文件
【发布时间】:2016-12-06 02:57:42
【问题描述】:

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

【问题讨论】:

    标签: ios filesystems ios-app-extension


    【解决方案1】:

    为了使文件可用于应用扩展,您必须使用Group Path,因为应用扩展无法访问应用的文档文件夹,因此您必须按照以下步骤操作,

    1. Project Settings-> Capabilities启用App Groups
    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/ 文件夹。
    • 嗨@iphonic 你对这个问题有任何想法stackoverflow.com/questions/55547930/…
    • 我想在扩展项目中写入日志,我在应用组共享文件夹中创建了文件,但它仍然无法在文件中写入数据,你知道为什么吗?
    • @Anita 你找到了登录共享容器扩展的解决方案吗?
    • 是的,我们无法访问应用程序访问文件的文档文件夹,在应用程序和扩展程序中您需要使用共享文件夹检查:developer.apple.com/library/archive/documentation/General/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多