在這裡,我將作出一些建議來回答上述問題。常見的建立http請求的方式主要有兩種:同步和非同步。在這裡,我們將對這兩種方式作一一討論。
在objective C,可以使用NSURL、NSURLRequest和NSURLConnection來建立http請求,而在Swift,它們同樣的適用。讓我們從同步呼叫開始吧。
同步呼叫:
var urlString = "http://api.shephertz.com"// Your Normal URL String var url = NSURL.URLWithString(urlString)// Creating URL var request = NSURLRequest(URL: url) // Creating Http Request var response:AutoreleasingUnsafePointer<NSURLResponse?> = nil; var error: AutoreleasingUnsafePointer<NSErrorPointer?> = nil; // Sending Synchronous request using NSURLConnection var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: response, error:nil) as NSData iferror != nil { // You can handle error response here } else { //Converting data to String var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding) }
如果響應的是JSON格式,你可以直接把它解析到NSArray / NSDictionary格式:
var responseDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData,options: NSJSONReadingOptions.MutableContainers, error:nil) as NSDictionary
非同步呼叫:
非同步呼叫可以使用委託模式或者使用objective-c中的completion handler。
使用completion handler:
var urlString = "http://api.shephertz.com"// Your Normal URL String var url = NSURL.URLWithString(urlString)// Creating URL var request = NSURLRequest(URL: url)// Creating Http Request // Creating NSOperationQueue to which the handler block is dispatched when the request completes or failed var queue: NSOperationQueue = NSOperationQueue() // Sending Asynchronous request using NSURLConnection NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in iferror != nil { println(error.description) self.removeActivityIndicator() } else { //Converting data to String var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding) } })使用委託模式:
var urlString = "http://api.shephertz.com"// Your Normal URL String var url = NSURL.URLWithString(urlString)// Creating URL var request = NSURLRequest(URL: url)// Creating Http Request //Making request var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)
在這裡,如果要讓connection一開始就立刻載入資料,可把startImmediately的值設定為true,否則就設定為false。如果你使用的是false,則connection將會被設定為不在run loop下執行。你可以在之後通過呼叫scheduleInRunLoop(_aRunLoop:NSRunLoop!,forMode mode:String!)來將connection設定為進入run loop執行和你所選擇的模式。
現在你可以建立請求,但是你需要定義在這種情況下的作為響應的委託。
在上面的程式碼中,我們傳遞委託來作為self,因此包含的類應當與NSURLConnectionDataDelegate一致,並且類中也應當定義以下委託函式:
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { //It says the response started coming NSLog("didReceiveResponse") }
你還應當定義一個全域性的NSMutableData變數:
var data = NSMutableData()
這裡還有一種可能性是資料可能以塊的形式存在。如果資料是以分批的形式接受到的,那麼以下的委託函式將會把這些資料收整合塊並新增到已定義的全域性資料變數。
func connection(connection: NSURLConnection!, didReceiveData _data: NSData!) { //This will be called again and again until you get the full response NSLog("didReceiveData") // Appending data self.data.appendData(_data) } func connectionDidFinishLoading(connection: NSURLConnection!) { // This will be called when the data loading is finished i.e. there is no data left to be received and now you can process the data. NSLog("connectionDidFinishLoading") var responseStr:NSString = NSString(data:self.data, encoding:NSUTF8StringEncoding) }
本文作者將整個程式碼封裝在了一個示例專案裡,你可以在my github repo上進行下載。
相關閱讀
評論(1)