分享

如何在Swift语言中创建http请求

pig2 发表于 2015-2-27 17:44:14 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 0 15485

问题导读

1.异步调用可以使用那些模式?
2.同步条用和异步调用有哪些区别?






如果你对Objective-C比较了解的话,对于如何创建http请求你一定驾轻就熟了,而新语言Swift与其相比只有语法上的区别。但是,对才接触到这个崭新平台的初学者来说,他们仍然想知道“如何在Swift语言中创建http请求?”。

在这里,我将作出一些建议来回答上述问题。常见的创建http请求的方式主要有两种:同步和异步。在这里,我们将对这两种方式作一一讨论。

在objective C,可以使用NSURL、NSURLRequest和NSURLConnection来创建http请求,而在Swift,它们同样的适用。让我们从同步调用开始吧。


同步调用:
  1. var urlString = "http://api.shephertz.com" // Your Normal URL String
  2. var url = NSURL.URLWithString(urlString)// Creating URL
  3. var request = NSURLRequest(URL: url) // Creating Http Request
  4. var response:AutoreleasingUnsafePointer<NSURLResponse?> = nil;
  5. var error: AutoreleasingUnsafePointer<NSErrorPointer?> = nil;
  6. // Sending Synchronous request using NSURLConnection
  7. var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: response, error:nil) as NSData
  8. if error != nil
  9. {
  10.    // You can handle error response here
  11. }
  12. else
  13. {
  14.    //Converting data to String
  15.     var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding)
  16. }
复制代码


如果响应的是JSON格式,你可以直接把它解析到NSArray / NSDictionary格式:
  1. var responseDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData,options: NSJSONReadingOptions.MutableContainers, error:nil) as NSDictionary
复制代码



异步调用:
异步调用可以使用委托模式或者使用objective-c中的completion handler。
使用completion handler:
  1. var urlString = "http://api.shephertz.com" // Your Normal URL String
  2. var url = NSURL.URLWithString(urlString)// Creating URL
  3. var request = NSURLRequest(URL: url)// Creating Http Request
  4.   
  5. // Creating NSOperationQueue to which the handler block is dispatched when the request completes or failed
  6. var queue: NSOperationQueue = NSOperationQueue()
  7.   
  8. // Sending Asynchronous request using NSURLConnection
  9. NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in
  10.   
  11.         if error != nil
  12.         {
  13.             println(error.description)
  14.             self.removeActivityIndicator()
  15.         }
  16.         else
  17.         {
  18.             //Converting data to String
  19.             var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding)
  20.          }
  21.     })
复制代码

使用委托模式:

  1. var urlString = "http://api.shephertz.com" // Your Normal URL String
  2. var url = NSURL.URLWithString(urlString)// Creating URL
  3. var request = NSURLRequest(URL: url)// Creating Http Request
  4. //Making request
  5. 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一致,并且类中也应当定义以下委托函数:

  1. func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
  2. { //It says the response started coming
  3.     NSLog("didReceiveResponse")
  4. }
复制代码
你还应当定义一个全局的NSMutableData变量:
  1. var data = NSMutableData()
复制代码
这里还有一种可能性是数据可能以块的形式存在。如果数据是以分批的形式接受到的,那么以下的委托函数将会把这些数据收集成块并添加到已定义的全局数据变量。

  1. func connection(connection: NSURLConnection!, didReceiveData _data: NSData!)
  2. { //This will be called again and again until you get the full response
  3.     NSLog("didReceiveData")
  4.     // Appending data
  5.     self.data.appendData(_data)
  6. }
  7.   
  8. func connectionDidFinishLoading(connection: NSURLConnection!)
  9. {
  10. // 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.
  11.     NSLog("connectionDidFinishLoading")
  12.     var responseStr:NSString = NSString(data:self.data, encoding:NSUTF8StringEncoding)
  13. }
复制代码
本文作者将整个代码封装在了一个示例项目里,你可以在my github repo上进行下载。



转载自慧都控件网

没找到任何评论,期待你打破沉寂

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条