0

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):

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Witterquick
  • 6,048
  • 3
  • 26
  • 50
  • 1
    Most probably, "stringByAppendingString" should be "stringByAppendingPathComponent" (or better, "URLByAppendingPathComponent") – If you log the created paths then you'll see that the path separator "/" is missing :) – Martin R Jun 26 '16 at 17:07
  • Thanks! that was it. Post it as an answer and I'll accept as the correct one – Witterquick Jun 26 '16 at 17:15

1 Answers1

3

The problem is unrelated to app extensions or CocoaLumberjack.

stringByAppendingString just concatenates strings, so that the path separator "/" is missing in the generated directory name.

There was a dedicated method stringByAppendingPathComponent, which however has been deprecated in Objective-C and is no longer available in Swift. You should operate on the URL by using URLByAppendingPathComponent instead:

let extensionLogDirectory = containerUrl?.URLByAppendingPathComponent("AppExtensionLogs").path
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382