斯威夫特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")
}
stringByAppendingPathComponent不会在Xcode 7工作(不推荐)。其中就是为什么我使用URLByAppendingPathComponent。 – jithin
我正在使用xcode 7.1。我没有被弃用的问题。不过,我已经更新了代码。 –
你有没有测试上面的例子?它是否解决了你的问题@jithin? –