Search code examples
iosswiftfile-managerfilehandler

When I am appending every string to .txt file by using try String(contentsOf: shareLog) in swift failing Some times


I am calling bellow function to get contentsof the .txt file and I am getting successfully some times but some times when I am trying to get It Is going to catch block and giving the bellow error ..please help me out

// Used for sharing

func getLogData(file: String) -> String? {

    let shareLog = dir.appendingPathComponent(file, isDirectory: false)

    if fileManager.fileExists(atPath: shareLog.path) {
        do {
            let result1 = try String(contentsOf: shareLog)
            print(result1)
            return result1
        } catch let error as NSError {
            print("Failed reading from file: \(error)")
            return nil
        }

    }

    print("Failed to get log at: \(logPath)")
    return nil
}

//Error when try to get .txt file contentsof

Error Domain=NSCocoaErrorDomain Code=264 "The file “somelog-log.txt” couldn’t be opened because the text encoding of its contents can’t be determined." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/199D8E4D-6DFC-4327-BC57-06957BCC6EA3/Documents/somelog-log.txt}


Solution

  • Specify the encoding explicitly

    let result1 = try String(contentsOf: shareLog, encoding: .utf8)