iOS Widget Intent Handler无法访问App Group文件夹的解决咨询
问题:Widget Intent Handler读取App Group目录失败
我正在为Widget编写Intent Handler,代码如下:
extension FileManager { static var appGroupURLAsText: String { `default`.containerURL(forSecurityApplicationGroupIdentifier: "group.com.emojiApp.EmojiWidget")!.absoluteString } } extension IntentHandler: SelectEmojiIntentHandling { func provideEmojiOptionsCollection( for intent: SelectEmojiIntent, with completion: @escaping (INObjectCollection<EmojiINO>?, Error?) -> Void ) { print("stuff happening in intent handler") print(FileManager.appGroupURLAsText) let fm = FileManager.default print("after declaring fm") var items = [String]() do { print("inside of do") items = try fm.contentsOfDirectory(atPath: FileManager.appGroupURLAsText) print("after declaring items") } catch { print("Unexpected error: \(error).") // failed to read directory – bad permissions, perhaps? } //I don't believe the code below is relevant to the error but I'm including it here in case var emojiItems = [EmojiINO]() for item in items { let finalThing = EmojiINO(identifier: item, display: item) emojiItems.append(finalThing) } completion(INObjectCollection(items: emojiItems), nil) } }
在iOS 15.5的iPhone 13 Pro模拟器中运行时,控制台输出如下:
stuff happening in intent handler file:///Users/myname/Library/Developer/CoreSimulator/Devices/86836E5F-4CA8-4288-899F-0CA595F18525/data/Containers/Shared/AppGroup/4AD329B4-32C5-40EE-BEBF-BFC2BDDB34F9/ after declaring fm inside of do Unexpected error: Error Domain=NSCocoaErrorDomain Code=260 "The folder “4AD329B4-32C5-40EE-BEBF-BFC2BDDB34F9” doesn’t exist." UserInfo={NSUserStringVariant=( Folder ),
代码无法执行到"after declaring items"打印语句,确认问题出在contentsOfDirectory方法。我已在Finder中确认该App Group文件夹存在且URL有效,请问该如何修复此问题?
解决方案
问题出在appGroupURLAsText属性返回的是URL的带协议头字符串形式(包含file://前缀),而contentsOfDirectory(atPath:)方法需要的是本地文件系统的纯路径字符串(不带协议头)。
修改FileManager的扩展代码,将absoluteString替换为path:
extension FileManager { static var appGroupURLAsText: String { `default`.containerURL(forSecurityApplicationGroupIdentifier: "group.com.emojiApp.EmojiWidget")!.path } }
原因说明
absoluteString返回完整的URL格式字符串,包含file://协议标识,这种格式不符合contentsOfDirectory(atPath:)的参数要求,导致系统无法识别为有效本地路径。path属性直接返回本地文件系统的路径字符串,不带任何协议头,是FileManager文件操作方法所需的正确格式。
修改后,contentsOfDirectory(atPath:)即可正确识别并读取目标App Group目录。
内容的提问来源于stack exchange,提问作者Philip7899
相关产品推荐
相关产品推荐

