app扩展如何访问包含app Documents /文件夹的文件 [英] How can app extension access files in containing app Documents/ folder
问题描述
在app扩展程序中是否有办法从包含应用程序生成图像,该应用程序存储在/ var / mobile / Containers / Data / Application // Documents //文件夹中?
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?
推荐答案
为了使文件可用于应用扩展程序,您必须使用组路径
,因为App Extension无法访问应用程序的文档文件夹,因为您已按照这些步骤操作,
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,
- 启用应用程序群组来自项目设置 - >功能。
- 添加类似
group.yourappid $ c $的群组分机c>。
-
然后使用以下代码。
- Enable App Groups from Project Settings-> Capabilities.
- Add a group extension something like
group.yourappid
. 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.
注意 - 请记住,您需要在组文件夹而不是文档文件夹中生成图像,因此它适用于应用和扩展程序。
干杯。
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!)
}
这篇关于app扩展如何访问包含app Documents /文件夹的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!