如何使用Swift 2 + XCode 7 + iOS 9获取和解析JSON [英] How To Fetch and Parse JSON Using Swift 2 + XCode 7 + iOS 9
问题描述
正在寻找与Swift 2和iOS 9联网的有用教程,但似乎该主题在线上没有内容.我已经看过WWDC会话与NSURLSession联网,但是我无法适应iOS9的新API具有异步方式来获取和解析JSON数据.我尝试过的:
Was looking for useful tutorials for networking with Swift 2 and iOS 9, but it seems that topic has no content online. I have watched the WWDC session Networking with NSURLSession But I couldn't adapt the new API of iOS9 to have an asynchronous way to fetch and parse JSON data. What I have tried:
do {
if let url = NSURL(string: "site/api.php?option=fetchOps"),
let data = NSData(contentsOfURL: url),
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String:AnyObject]] {
}
} catch let error as NSError {
print(error.description)
}
请分享您在iOS9和Swift2上的联网经验,是否有任何最佳实践,例如用于联网和解析的Singleton类,也许是ORM?
Please share your experience with networking on iOS9 and Swift2, any best practices maybe a Singleton class for networking and parsing maybe an ORM ?
推荐答案
轻松为您提出请求的方式:
或者如果您想自己发送请求:
Or If you want to send request by your own:
仅作为示例,在这里我已经转换了NSString
Just as an example, here I've converted a NSString
首先将NSString转换为NSDictionary
First of all convert the NSString to NSDictionary
static func convert(src: NSString) -> NSDictionary {
// convert String to NSData
let data = src.dataUsingEncoding(NSUTF8StringEncoding)
var error: NSError?
// convert NSData to 'AnyObject'
let anyObj: AnyObject?
do {
anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
} catch let error1 as NSError {
error = error1
anyObj = nil
}
if(error != nil) {
// If there is an error parsing JSON, print it to the console
print("JSON Error \(error!.localizedDescription)")
//self.showError()
return NSDictionary()
} else {
return anyObj as! NSDictionary
}
}
然后像这样使用它
if let name = dictionary["name"] as? String {
self.name = name
}
您可以使用转换后的JSON来创建这样的对象
You can use the converted JSON to make an object like this
import Foundation
class Student {
var name="";
init(dictionary: NSDictionary) {
let _NAME = "name"
if let name = dictionary[_NAME] as? String {
self.name = name
}
}
}
这篇关于如何使用Swift 2 + XCode 7 + iOS 9获取和解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!