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

概述:本文通过实例从同步和异步两种方式上回答了”如何在Swift语言中创建http请求“的问题。

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

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

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

同步调用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
if error != nil
{
    // You can handle error response here
}
else
{
    //Converting data to String
     var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding)
}

如果响应的是JSON格式,你可以直接把它解析到NSArray / NSDictionary格式:

?
1
var responseDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData,options: NSJSONReadingOptions.MutableContainers, error:nil) as NSDictionary

异步调用:

异步调用可以使用委托模式或者使用objective-c中的completion handler。

使用completion handler:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
  
         if error != nil
         {
             println(error.description)
             self.removeActivityIndicator()
         }
         else
         {
             //Converting data to String
             var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding)
          }
     })

使用委托模式:

?
1
2
3
4
5
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一致,并且类中也应当定义以下委托函数:

?
1
2
3
4
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
//It says the response started coming
     NSLog( "didReceiveResponse" )
}

你还应当定义一个全局的NSMutableData变量:

?
1
var data = NSMutableData()

这里还有一种可能性是数据可能以块的形式存在。如果数据是以分批的形式接受到的,那么以下的委托函数将会把这些数据收集成块并添加到已定义的全局数据变量。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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上进行下载。

猜你喜欢

转载自shoothao.iteye.com/blog/2187327