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

前端之家收集整理的这篇文章主要介绍了Swift - 使用NSURL进行数据的提交和获取(POST与GET)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用Swift进行iOS开发时,不可避免的要进行远程的数据获取和提交。

其数据请求的方式既可能是POST也可能是GET。同不管是POST还是GET又可以分为同步请求和异步请求。
下面通过四个例子来进行演示。

1,使用POST方式提交数据(用户id和分数)
(1)同步请求
1
2
3
4
5
6
7
8
9
10
@H_403_42@ 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: = "@L_301_0@"
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 NSURLConnectionDataDelegate
{
//保存分数
)
{
!
(string:urlString)
:url)
"score=\(score)&user=\(userid)"
//编码POST数据
NSASCIIStringEncoding )
//保用 POST 提交
"POST"
= postData
conn: !
conn = (request: request,delegate: self )
conn.start()
(conn)
}
connection(connection: )
( "请求成功!" );
(response)
}
)
@H_403_413@{
"请求成功1!" );
(data:data,monospace!important; min-height:auto!important">)
(datastring)
}
connectionDidFinishLoading(connection: )
{
"请求成功2!" );
}
}

2,使用GET方式获取数据(用户id对应的分数)
(1)同步请求
25
//获取分数
getscore(user: ){
"GET"
//响应对象
?
@H_897_502@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)
@H_403_413@
//解析 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 原文链接:https://www.f2er.com/swift/321238.html

猜你在找的Swift相关文章