当我在 swift 中使用 try String(contentsOf: shareLog) 将每个字符串附加到 .txt 文件时有时会失败

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

我正在调用波纹管函数来获取 .txt 文件的内容,有时我会成功,但有时当我试图获取它时,它会捕获块并给出波纹管错误..请帮助我

// 用于分享

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
}

//尝试获取 .txt 文件内容时出错

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}

明确指定编码

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