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