iOS开发——网络Swift篇&NSURL进行数据请求(POST与GET)

NSURL进行数据请求(POST与GET)

 
使用Swift进行iOS开发时,不可避免的要进行远程的数据获取和提交。
其数据请求的方式既可能是POST也可能是GET。同不管是POST还是GET又可以分为同步请求和异步请求。
下面通过四个例子来进行演示。
 
1,使用POST方式提交数据(用户id和分数)

(1)同步请求

 //保存分数
 func saveScore(score:Int, userid:String)
 {
     let urlString:String = "http://hangge.com/"
     var url:NSURL!
     url = NSURL(string:urlString)
     var request = NSMutableURLRequest(URL:url)
     var body = "score=\(score)&user=\(userid)"
     //编码POST数据
     var postData = body.dataUsingEncoding(NSUTF8StringEncoding)
     //保用 POST 提交
     request.HTTPMethod = "POST"
     request.HTTPBody = postData

     //响应对象
     var response:NSURLResponse?
     //错误对象
     var error:NSError?

     //发出请求
     var received:NSData? = NSURLConnection.sendSynchronousRequest(request,
         returningResponse: &response, error: &error)

     if(error != nil){
         println(error?.code)
         println(error?.description)
     }else{
         var datastring = NSString(data:received!, encoding: NSUTF8StringEncoding)
         println(datastring)
     }
 }

(2)异步请求

 import UIKit

 class ScoreController:NSObject, NSURLConnectionDataDelegate
 {
     //保存分数
     func saveScore(score:Int, userid:String)
     {
         let urlString:String = "http://hangge.com/savescore.php"
         var url:NSURL!
         url = NSURL(string:urlString)
         var request = NSMutableURLRequest(URL:url)
         var body = "score=\(score)&user=\(userid)"
         //编码POST数据
         var postData = body.dataUsingEncoding(NSASCIIStringEncoding)
         //保用 POST 提交
         request.HTTPMethod = "POST"
         request.HTTPBody = postData
         var conn:NSURLConnection!
         conn = NSURLConnection(request: request,delegate: self)
         conn.start()
         println(conn)
     }

     func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
     {
         println("请求成功!");
         println(response)
     }

     func connection(connection: NSURLConnection!, didReceiveData data: NSData!)
     {
         println("请求成功1!");
         var datastring = NSString(data:data, encoding: NSUTF8StringEncoding)
         println(datastring)
     }

     func connectionDidFinishLoading(connection: NSURLConnection!)
     {
         println("请求成功2!");
     }
 }
2,使用GET方式获取数据(用户id对应的分数)

(1)同步请求

 //获取分数
 func getScore(user:String){

     let urlString:String="http://hangge.com/getscore.php?user=\(user)"
     var url:NSURL!
     url = NSURL(string:urlString)
     var request = NSMutableURLRequest(URL:url)
     request.HTTPMethod = "GET"

     //响应对象
     var response:NSURLResponse?
     //错误对象
     var error:NSError?

     //发出请求
     var received:NSData? = NSURLConnection.sendSynchronousRequest(request,
         returningResponse: &response, error: &error)

     if(error != nil){
         println(error?.code)
         println(error?.description)
     }else{
         var datastring = NSString(data:received!, encoding: NSUTF8StringEncoding)
         println(datastring)
     }
 }

(2)异步请求

 import UIKit

 class ScoreController:NSObject, NSURLConnectionDataDelegate
 {
     //获取分数
     func getScore(user:String)
     {
         let urlString:String="http://hangge.com/getscore.php?user=\(user)"
         var url:NSURL!
         url = NSURL(string:urlString)
         var request = NSMutableURLRequest(URL:url)

         var body = "user=\(user)"
         request.HTTPMethod = "GET"
         var conn:NSURLConnection!
         conn = NSURLConnection(request: request,delegate: self)
         conn.start()
         println(conn)
     }

     func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
     {
         println("请求成功!");
         println(response)
     }

     func connection(connection: NSURLConnection!, didReceiveData data: NSData!)
     {
         println("请求成功1!");
         var datastring = NSString(data:data, encoding: NSUTF8StringEncoding)
         println(datastring)
         //解析 JSON 数据
         var json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data,
             options:NSJSONReadingOptions.AllowFragments,error:nil)

         var score = json.objectForKey("score") as Int
         println(score)
     }

     func connectionDidFinishLoading(connection: NSURLConnection!)
     {
         println("请求成功2!");
     }
 }
 
上一篇:【Ray Tracing The Next Week 超详解】 光线追踪2-7 任意长方体 && 场景案例


下一篇:Android Studio利用异步任务AsyncTask发送post请求获取json数据