简体   繁体   中英

writetofile always returns false

I am trying to write content to a file in 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)

But content is not written to file and status is always false

You can't write to your application's bundle. Instead, try writing to your application's documents directory. See this question: Write a file on iOS

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

If you already have a file in bundle, Use following code to find path and read file.

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

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

Parse Web service response :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM