swift中的网络请求——NSURLConnection

来源:互联网 发布:英语听力复读软件 编辑:程序博客网 时间:2024/06/10 04:49

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

效果图


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

// NSURLlet 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 {                            }        }}

// NSURLlet 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? = nildo {            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 {                            }}


原创粉丝点击