gpt4 book ai didi

ios - writetofile 总是返回 false

转载 作者:行者123 更新时间:2023-11-30 13:38:25 28 4
gpt4 key购买 nike

我正在尝试用 swift 将内容写入文件

let jsonResult = try!   NSJSONSerialization.JSONObjectWithData(response.data, options:   NSJSONReadingOptions.MutableContainers) as! NSDictionary   

let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

let documentDirectory = urls.first!.path
let path = NSURL(fileURLWithPath: documentDirectory!).URLByAppendingPathComponent("data.txt")
let dict = jsonResult as NSDictionary
let status = dict.writeToFile(path.path!, atomically: false)
print(status)

但内容未写入文件且状态始终为 false

最佳答案

swift 2

        let file = "file.txt" //this is the file. we will write to and read from it

let jsonResult : NSMutableDictionary = NSMutableDictionary.init(object: "08:00:00", forKey: "start_hour");
jsonResult.setValue("10:00:00", forKey: "end_hour");
jsonResult.setValue("30", forKey: "call_duration");

let dict = jsonResult as NSDictionary

if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir as String).URLByAppendingPathComponent(file);

//writing
dict.writeToFile(path.path!, atomically: false)

var contents : NSString
//reading
do {
contents = try NSString(contentsOfFile: path.path!, encoding: NSUTF8StringEncoding)
}
catch {
/* error handling here */
contents = ""
}
print(contents as String);
}

如果 bundle 中已有文件,请使用以下代码查找路径并读取文件。

    let path = NSBundle.mainBundle().pathForResource("sample-text", ofType: "txt")

let contents: NSString
do {
contents = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
} catch _ {
contents = ""
}

解析 Web 服务响应:

        // responseData - API response data.

// parse the result as JSON, since that's what the API provides
let getConfig: NSDictionary
do {
getConfig = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions()) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
}

关于ios - writetofile 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836793/

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