码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-09-25 16:03:12      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

使用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
31
//保存分数
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)异步请求

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://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)同步请求

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
//获取分数
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)异步请求

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
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!");
    }
}

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

标签:

原文地址:http://www.cnblogs.com/Free-Thinker/p/4838409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!