概述:本文通过实例从同步和异步两种方式上回答了”如何在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
|
// 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
error != nil
{
println(error.description)
self.removeActivityIndicator()
}
else
{
//Converting data to String
})
|
使用委托模式:
1
2
3
4
5
|
// 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!,forModemode:String!)来将connection设定为进入run loop运行和你所选择的模式。
现在你可以创建请求,但是你需要定义在这种情况下的作为响应的委托。
在上面的代码中,我们传递委托来作为self,因此包含的类应当与NSURLConnectionDataDelegate一致,并且类中也应当定义以下委托函数: