在应用程序扩展中,是否有一种方法可以获取从包含应用程序生成的图像,存储在 /var/mobile/Containers/Data/Application//Documents// 文件夹中?
在应用程序扩展中,是否有一种方法可以获取从包含应用程序生成的图像,存储在 /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;
}
您可以根据要生成的图像扩展名添加或更改路径扩展名。
注意 - 记住,您需要在组文件夹中生成图像,而不是在“文档”文件夹中生成图像,以便应用程序和扩展程序都可以使用。
干杯。
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!)
}