writetofile总是返回false

时间:2016-03-07 05:31:11

标签: ios swift swift2 xcode7

我正在尝试用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

2 个答案:

答案 0 :(得分:0)

您无法写入应用程序的捆绑包。相反,请尝试写入应用程序的文档目录。请参阅此问题:Write a file on iOS

答案 1 :(得分:0)

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);
        }

如果您已在捆绑包中存在文件,请使用以下代码查找路径和读取文件。

    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")
        }