学习地址: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, 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 {
}
}