gpt4 book ai didi

ios - ContentsOfFile 方法在 swift 2.2 中弃用

转载 作者:搜寻专家 更新时间:2023-10-31 21:49:42 30 4
gpt4 key购买 nike

我在 Objective-C 中的代码是

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Logger.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

当我尝试将它转换为 swift 时,我无法转换它,因为方法 ContentsOfFile 已被弃用。谁能告诉我如何将其转换为 swift?我正在使用 Xcode 7.2 和 swift 2.2。我在 swift 中的代码是

var paths : NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : NSString = paths[0] as! String
var filePath = documentsDirectory.stringByAppendingPathComponent("Logger.txt")
var error:NSError?
let content = NSString(contentsOfFile: filePath, encoding:NSUTF8StringEncoding, error: &error)
if let theError = error {
NSLog("\(theError.localizedDescription)")
}

最佳答案

swift 2+

let path:String = NSBundle.mainBundle().pathForResource("Logger", ofType: "txt")!
txtContent.text = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding)

swift 3+

let path:String = Bundle.main.path(forResource: "Logger", ofType: "txt")!
txtContent.text = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)

关于ios - ContentsOfFile 方法在 swift 2.2 中弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36123596/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com