0%

[swift] NetWork (2) 非同步方式取得API資訊

為了避免撈取API資料太久而讓整個APP卡住,所以建議撈取API資料時都另外開出一個queue來非同步執行 ```swift
var url:NSURL = NSURL(string: “http://xxx.com.tw/api/getdata")!;
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 10);
request.HTTPMethod = “POST”;
request.HTTPBody = “yourdata”.dataUsingEncoding(NSUTF8StringEncoding);

//新增一個queue來執行API,避免API撈取資料太久把整個APP卡住
let queue :NSOperationQueue = NSOperationQueue();
//非同步方式取得資料
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err:String? = error?.description;
if(data != nil && error == nil)
{
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding);
println(“responseString = (responseString)”);
}
});