swift 网络请求 Get、Post HttpRequest For Swift language (iOS )

来源:互联网 发布:战争程序员白濑 编辑:程序博客网 时间:2024/06/02 05:50

1.Xcode7后注意HTTP请求的处理: Add  "NSAppTransportSecurity (NSAllowsArbitraryLoads Boolean YES)" in info.plist


2.Get:

 let url_origin = "http://..."

       let url_percent = url_origin.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

        let url:NSURL =NSURL(url_percent!)!

       let requets:NSURLRequest =NSURLRequest(URL: url)

        let configuration:NSURLSessionConfiguration =NSURLSessionConfiguration.defaultSessionConfiguration()

       let session:NSURLSession =NSURLSession(configuration: configuration)

        let task:NSURLSessionDataTask = session.dataTaskWithRequest(requets, completionHandler: {

                    (data:NSData?,response:NSURLResponse?,error:NSError?)->Voidin

                    if error == nil{

                        do{

                            let responseData:NSDictionary =try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments) as! NSDictionary

                            print(responseData)

   //如果responseData是Json格式,可以通过 responseData["key的名字"] 来获取相应的value值 if the form of the responseData is "Json" , we can get the value through responseData["the name of key"]

                        }catch{       

                        }

                    }

                })

                task.resume() //start task


3.Post:

 let request =NSMutableURLRequest(URL:NSURL(string:"http://...?")!)

request.HTTPMethod ="POST"

    let postStr = "key=value&key2=value2&...&keyN=valueN"

                request.HTTPBody = postStr.dataUsingEncoding(NSUTF8StringEncoding)

                let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {

                    (data:NSData?,response:NSURLResponse?,error:NSError?)->Voidin

                    if error == nil{

                        do{

                            let responseString =NSString(data: data!, encoding: NSUTF8StringEncoding)

                            print("Post result \(responseString)")   

//根据返回结果进行解析做进一步处理  further processing                

                        }catch{

                            print("error")

                        }

                    }

                })

                task.resume()


0 0
原创粉丝点击