swift中的网络请求——NSURLConnection

前端之家收集整理的这篇文章主要介绍了swift中的网络请求——NSURLConnection前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

学习地址:https://github.com/potato512/SYSwiftLearning

效果


在swift中使用NSURLConnection进行网络请求

// NSURL
let url:NSURL = NSURL(string:"http://rapapi.org/mockjsdata/22598/userloginGet")!
// 请求(可以改的请求)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
// 默认就是GET请求
request.HTTPMethod = "GET"
// 发起请求
NSURLConnection.sendAsynchronousRequest(request,queue:NSOperationQueue()) {
                (response,data,error)in
            
            print(response)
            print(data)
            print(error)
            
            do {
//                let result = NSString(data: data!,encoding:NSUTF8StringEncoding)
                
                let result:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!,options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                print(result)
                
                dispatch_async(dispatch_get_main_queue(),{
                    () -> Void in
                    let message:String = result.objectForKey("msg") as! String
                    let alert = UIAlertView(title: nil,message: message,delegate: nil,cancelButtonTitle: "OK")
                    alert.show()
                })
                
            } catch {
                
            }
        }
}

// NSURL
let url:NSURL = NSURL(string:"http://rapapi.org/mockjsdata/22598/userloginPostWithParams")!
// 请求(可以改的请求)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
// POST请求
request.HTTPMethod = "POST"
// 数据体
let params:NSMutableDictionary = NSMutableDictionary()
params["userName"] = "devZhang"
params["userPassword"] = "devZhang"
var jsonData:NSData? = nil
do {
            jsonData  = try NSJSONSerialization.dataWithJSONObject(params,options:NSJSONWritingOptions.PrettyPrinted)
        } catch {
            
}
// 将字符串转换成数据
request.HTTPBody = jsonData
// 发起请求
NSURLConnection.sendAsynchronousRequest(request,queue:NSOperationQueue()) {
            (response,cancelButtonTitle: "OK")
                    alert.show()
                })
                
            } catch {
                
            }

}
原文链接:https://www.f2er.com/swift/321412.html

猜你在找的Swift相关文章