微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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: = "http://www.hangge.com/"
var url: NSURL !
url = (string:urlString)
request = NSMutableuRLRequest ( URL :url)
body = "score=\(score)&user=\(userid)"
//编码POST数据
postData = body.dataUsingEncoding( NSUTF8StringEncoding )
//保用 POST 提交
request. HTTPMethod "POST"
HTTPBody = postData
//响应对象
response: NSURLResponse ?
do{
//发出请求
received: NSData ? = try NSURLConnection .sendSynchronousRequest(request,
returningResponse: &response)
datastring = Nsstring (data:received!,encoding: )
print (datastring)
}catch error as NSError {
//打印错误消息
(error.code)
(error.description)
}
}

(2)异步请求
30
31
32
33
34
35
36
37
38
39
40
41
import UIKit
class scoreController : NSObject ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas, NSURLConnectionDataDelegate
{
//保存分数
)
{
!
(string:urlString)
:url)
"score=\(score)&user=\(userid)"
//编码POST数据
NSASCIIStringEncoding )
//保用 POST 提交
"POST"
= postData
conn: !
conn = (request: request,delegate: self )
conn.start()
(conn)
}
connection(connection: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,didReceiveResponse response: )
( "请求成功!" );
(response)
}
)
{
"请求成功1!" );
(data:data,monospace!important; min-height:inherit!important">)
(datastring)
}
connectionDidFinishLoading(connection: )
{
"请求成功2!" );
}
}

2,使用GET方式获取数据(用户id对应的分数)
(1)同步请求
25
//获取分数
getscore(user: ){
"GET"
//响应对象
?
do{
//发出请求
returningResponse: &response)
)
(datastring)
{
//打印错误消息
(error.code)
(error.description)
}
}

(2)异步请求
41
42
43
44
45
46
47
48
49
50
//获取分数
"GET"
!
)
conn.start()
(conn)
}
)
{
);
(response)
)
{
);
)
(datastring)
//解析 JSON 数据
do {
json : AnyObject ! = try NSJSONSerialization . JSONObjectWithData (data,
options: NSJSONReadingOptions AllowFragments )
score = json.objectForKey( "score" ) as ! Int
{
//打印错误消息
(error.code)
(error.description)
}
}
)
{
);
}
}

原文出自: www.hangge.com 转载请保留原文链接 http://www.hangge.com/blog/cache/detail_670.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐