看看swift的几种常见的网络访问数据的方式:
1.NSURL + NSData + json解析
var url = NSURL(string: "http://localhost:18080/jsonserver/getNews")
var data = NSData(contentsOfURL: url!)var str = NSString(data: data!,encoding: NSUTF8StringEncoding)
var json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data!,options: NSJSONReadingOptions.AllowFragments,error: nil)
let news: AnyObject = json.objectForKey("newsList")!
list = news as! NSMutableArray;
这种方法是同步的网络访问,适合数据量小的服务,如果数据太大则会出现卡死,而且不好进行错误处理和调试
2. NSURL + NSURLRequest + NSURLConnection
func requestUrl(urlString: String){ var url: NSURL = NSURL(string: urlString) let request: NSURLRequest = NSURLRequest(URL: url) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response, data, error) -> Void in if error? { //Handle Error here }else{ //Handle data in NSData type } }) }这种方式,错误和成功的处理都在一个函数中,如果处理的东西比较复杂,则写的代码会比较乱.好处是效率比第三方的好.
let request = YYHRequest(url: NSURL(string: "http://www.google.com/")) request.loadWithCompletion { response, error in // request complete! }这种方式跟上个一样,处理函数都在一起,这个第三方库对上面的方式进行的封装,所以使用更简单.
4.SwiftHTTP库通过对NSURLSession进行封装
var request = HTTPTask() request.GET("http://vluxe.io", parameters: nil, success: {(response: AnyObject?) -> Void in },failure: {(error: NSError) -> Void in })成功和失败的处理终于分开
5.swift通过桥接oc的AFNetworking
库实现(<ProjectName>-Bridging-Header.h
)
func requestUrl(urlString: String) { let manager = AFHTTPRequestOperationManager() let params = ["a":1, "b":2] manager.GET(urlString, parameters: params, success: { (operation: AFHTTPRequestOperation!, responSEObject: AnyObject!) in let responseDict = responSEObject as NSDictionary! }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in //Handle Error }) }
关于返回结果的解析以前都用NSJSONSerialization,let news: AnyObject = json.objectForKey("newsList")!这种方式,操作比较复杂,还要可选绑定判断
swift的话推荐用SwiftyJSON
,不过我还没有用成功,好像最新的xcode 7不支持try关键字.(response是AnyObject)
let json = JSONValue(dataFromNetworking) if let userName = json[999999]["wrong_key"]["wrong_name"].string{ //冷静,嘿嘿~ 调用不存在的["wrong_key]也不会crash滴, .string最终能安全的返回一个字符串或`nil` }原文链接:https://www.f2er.com/swift/325839.html