将writeToFile始终返回false
问题描述:
我想写的内容到一个文件中迅速将writeToFile始终返回false
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)
,但内容不会写入文件和状态永远是假的
答
斯威夫特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);
}
如果您已经在捆绑文件,请使用如下代码找到路径和读取文件。
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")
}
答
你不能写你的应用程序包。相反,请尝试写入您的应用程序的文档目录。看到这个问题:Write a file on iOS
+0
@Aron Wojnowski我试过first.Please看到我的修改quetion – jithin
stringByAppendingPathComponent不会在Xcode 7工作(不推荐)。其中就是为什么我使用URLByAppendingPathComponent。 – jithin
我正在使用xcode 7.1。我没有被弃用的问题。不过,我已经更新了代码。 –
你有没有测试上面的例子?它是否解决了你的问题@jithin? –