Swift - 使用NSURL进行数据的提交和获取(POST与GET)

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

1,使用POST方式提交数据(用户id和分数)
(1)同步请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//保存分数
func  saveScore(score: Int , userid: String )
{
     let  urlString: String  "http://www.hangge.com/"
     var  url: NSURL !
     url =  NSURL (string:urlString)
     let  request =  NSMutableURLRequest ( URL :url)
     let  body =  "score=\(score)&user=\(userid)"
     //编码POST数据
     let  postData = body.dataUsingEncoding( NSUTF8StringEncoding )
     //保用 POST 提交
     request. HTTPMethod  "POST"
     request. HTTPBody  = postData
         
     //响应对象
     var  response: NSURLResponse ?
         
     do{
         //发出请求
         let  received: NSData ? = try  NSURLConnection .sendSynchronousRequest(request,
             returningResponse: &response)
         let  datastring =  NSString (data:received!, encoding:  NSUTF8StringEncoding )
         print (datastring)
             
     }catch  let  error  as  NSError {
         //打印错误消息
         print (error.code)
         print (error.description)
     }
}

(2)异步请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import  UIKit
 
class  ScoreController : NSObject NSURLConnectionDataDelegate
{
     //保存分数
     func  saveScore(score: Int , userid: String )
     {
         let  urlString: String  "http://www.hangge.com/savescore.php"
         var  url: NSURL !
         url =  NSURL (string:urlString)
         let  request =  NSMutableURLRequest ( URL :url)
         let  body =  "score=\(score)&user=\(userid)"
         //编码POST数据
         let  postData = body.dataUsingEncoding( NSASCIIStringEncoding )
         //保用 POST 提交
         request. HTTPMethod  "POST"
         request. HTTPBody  = postData
         var  conn: NSURLConnection !
         conn =  NSURLConnection (request: request,delegate:  self )
         conn.start()
         print (conn)
     }
     
     func  connection(connection:  NSURLConnection , didReceiveResponse response:  NSURLResponse )
     {
         print ( "请求成功!" );
         print (response)
     }
     
     func  connection(connection:  NSURLConnection , didReceiveData data:  NSData )
     {
         print ( "请求成功1!" );
         let  datastring =  NSString (data:data, encoding:  NSUTF8StringEncoding )
         print (datastring)
     }
     
     func  connectionDidFinishLoading(connection:  NSURLConnection )
     {
         print ( "请求成功2!" );
     }
}

2,使用GET方式获取数据(用户id对应的分数)
(1)同步请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//获取分数
func  getScore(user: String ){
         
     let  urlString: String = "http://www.hangge.com/getscore.php?user=\(user)"
     var  url: NSURL !
     url =  NSURL (string:urlString)
     let  request =  NSMutableURLRequest ( URL :url)
     request. HTTPMethod  "GET"
         
     //响应对象
     var  response: NSURLResponse ?
         
     do{
         //发出请求
         let  received: NSData ? = try  NSURLConnection .sendSynchronousRequest(request,
             returningResponse: &response)
         let  datastring =  NSString (data:received!, encoding:  NSUTF8StringEncoding )
         print (datastring)
             
     }catch  let  error  as  NSError {
         //打印错误消息
         print (error.code)
         print (error.description)
     }
}

(2)异步请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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)
         let  request =  NSMutableURLRequest ( URL :url)
         
         request. HTTPMethod  "GET"
         var  conn: NSURLConnection !
         conn =  NSURLConnection (request: request,delegate:  self )
         conn.start()
         print (conn)
     }
     
     func  connection(connection:  NSURLConnection , didReceiveResponse response:  NSURLResponse )
     {
         print ( "请求成功!" );
         print (response)
     }
     
     func  connection(connection:  NSURLConnection , didReceiveData data:  NSData )
     {
         print ( "请求成功1!" );
         let  datastring =  NSString (data:data, encoding:  NSUTF8StringEncoding )
         print (datastring)
         
         //解析 JSON 数据
         do {
             let  json :  AnyObject ! = try  NSJSONSerialization . JSONObjectWithData (data,
                 options: NSJSONReadingOptions . AllowFragments )
             
             let  score = json.objectForKey( "score" as Int
             print (score)
         }catch  let  error  as  NSError {
             //打印错误消息
             print (error.code)
             print (error.description)
         }
     }
     
     func  connectionDidFinishLoading(connection:  NSURLConnection )
     {
         print ( "请求成功2!" );
     }
}

原文出自: www.hangge.com   转载请保留原文链接: http://www.hangge.com/blog/cache/detail_670.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值