[英]Cannot find file in app extension's shared container
I want to write log file at my extension, and read it at my app. 我想在扩展名中写入日志文件,并在我的应用程序中读取它。 For this purpose, I'm using shared groups (so both the app and the extension would be able to read from the same file)
为此,我使用共享组(因此应用程序和扩展名都可以从同一文件读取)
I wrote the following code: 我写了以下代码:
Extension: 延期:
let fileManager = NSFileManager.defaultManager()
let containerUrl = fileManager.containerURLForSecurityApplicationGroupIdentifier("group.MyCompany.MyProj")
let extensionLogDirectory = containerUrl?.path?.stringByAppendingString("AppExtensionLogs")
let logFileManager = DDLogFileManagerDefault(logsDirectory: extensionLogDirectory)
PacketTunnelProvider.fileLogger = DDFileLogger(logFileManager: logFileManager)
PacketTunnelProvider.fileLogger!.rollingFrequency = 60*60*12
PacketTunnelProvider.fileLogger!.logFileManager.maximumNumberOfLogFiles = 1
DDLog.addLogger(PacketTunnelProvider.fileLogger)
App (just to read the log file): App(仅读取日志文件):
let fileManager = NSFileManager.defaultManager()
let containerUrl = fileManager.containerURLForSecurityApplicationGroupIdentifier("group.MyCompany.MyProj")
if let extensionLogDirectory = containerUrl?.path?.stringByAppendingString("AppExtensionLogs") {
do {
let directoryContents = try fileManager.contentsOfDirectoryAtPath(extensionLogDirectory)//always fails
for file in directoryContents {
let path = extensionLogDirectory.stringByAppendingString(file)
do {
let fileContents = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
NSLog("file: \(fileContents)")
}
catch {/* error handling here */
}
}
}
catch {/* error handling here */
NSLog("nope!")
}
But, something now right - it's seems like contentsOfDirectoryAtPath always fails with "no such file" error What's wrong in this code? 但是,现在正确了-似乎contentsOfDirectoryAtPath总是失败,并显示“无此类文件”错误该代码有什么问题?
The problem is unrelated to app extensions or CocoaLumberjack. 该问题与应用程序扩展或CocoaLumberjack无关。
stringByAppendingString
just concatenates strings, so that the path separator "/" is missing in the generated directory name. stringByAppendingString
仅连接字符串,因此在生成的目录名称中缺少路径分隔符“ /”。
There was a dedicated method stringByAppendingPathComponent
, which however has been deprecated in Objective-C and is no longer available in Swift. 有一个专用的方法
stringByAppendingPathComponent
,但是在Objective-C中已弃用,在Swift中不再可用。 You should operate on the URL by using URLByAppendingPathComponent
instead: 您应该改为使用
URLByAppendingPathComponent
对URL进行URLByAppendingPathComponent
:
let extensionLogDirectory = containerUrl?.URLByAppendingPathComponent("AppExtensionLogs").path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.