0%

[swift] NetWork (1) 以Get 和 Post方式傳送資料

用Post方式傳遞資料

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var url:NSURL = NSURL(string: "http://xxx.com.tw/api/postdata")!;
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 10);
request.HTTPMethod = "POST";
request.HTTPBody = "yourPostData".dataUsingEncoding(NSUTF8StringEncoding);

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
println("error=\(error)")
return
}

println("response = \(response)")

//將收到的資料轉成字串print出來看看
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume();

用Get方式傳遞資料 ```swift
var url:NSURL = NSURL(string: “http://xxx.com.tw/api/getdata?id=5008&id=5009")!;
let request:NSURLRequest = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 10);

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if error != nil {
println(“error=(error)”)
return
}

println(“response = (response)”)

let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(“responseString = (responseString)”)
}
task.resume();

```

這邊整理一下從網路上找的NSURLRequestCachePolicy相關資訊,轉載自:iOS?存?存

  • ReloadIgnoringCacheData:忽略Cache數據,直接從原始網址下載。
  • ReloadRevalidatingCacheData:驗證本地的數據和遠端數據是否相同,如果不同則下?遠端?據,否?使用本地數據。* ReturnCacheDataDontLoad:只使用cache?據,如果不存在cache,請求失敗;用於?有建立網路連接離線模式;* ReturnCacheDataElseLoad: 只有在cache中不存在data時才從原始地址下?。* UseProtocolCachePolicy: NSURLRequest默認的cache policy,使用Protocol協議定義。* ReloadIgnoringLocalAndRemoteCacheData:忽略本地和遠端的緩存數據,直接從原始地址下?,與ReloadIgnoringCacheData類似。