![](/img/trans.png)
[英]How to create/use a shared app group container as cache storage between containing app and it's extension in ios
[英]Cannot find file in app extension's shared container
我想在擴展名中寫入日志文件,並在我的應用程序中讀取它。 為此,我使用共享組(因此應用程序和擴展名都可以從同一文件讀取)
我寫了以下代碼:
延期:
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(僅讀取日志文件):
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!")
}
但是,現在正確了-似乎contentsOfDirectoryAtPath總是失敗,並顯示“無此類文件”錯誤該代碼有什么問題?
該問題與應用程序擴展或CocoaLumberjack無關。
stringByAppendingString
僅連接字符串,因此在生成的目錄名稱中缺少路徑分隔符“ /”。
有一個專用的方法stringByAppendingPathComponent
,但是在Objective-C中已棄用,在Swift中不再可用。 您應該改為使用URLByAppendingPathComponent
對URL進行URLByAppendingPathComponent
:
let extensionLogDirectory = containerUrl?.URLByAppendingPathComponent("AppExtensionLogs").path
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.