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格式:
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
if error != 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)