加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift中的网络请求——NSURLConnection

发布时间:2020-12-14 06:11:20 所属栏目:百科 来源:网络整理
导读:学习地址:https://github.com/potato512/SYSwiftLearning 效果图 在swift中使用 NSURLConnection进行网络请求 // NSURLlet url:NSURL = NSURL(string:"http://rapapi.org/mockjsdata/22598/userloginGet")!// 请求(可以改的请求)let request:NSMutableURLRe

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

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读