Swift 的 HTTP 开发包:SwiftHTTP

分享到:

SwiftHTTP是 Swift 语言中 NSURLSession的简单封装了 ,简化了 HTTP 请求操作。

Example

GET

The most basic request. By default an NSData object will be returned for the response.

var request = HTTPTask()
request.GET("http://vluxe.io", parameters: nil, success: {(response: HTTPResponse) -> Void in
if response.responseObject != nil {
let data = response.responseObject as NSData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println("response: \(str)") //prints the HTML of the page
}
},failure: {(error: NSError) -> Void in
println("error: \(error)")
})

We can also add parameters as with standard container objects and they will be properly serialized to their respective HTTP equivalent.

var request = HTTPTask()
request.GET("http://google.com", parameters: ["param": "param1", "array": ["first array element","second","third"], "num": 23], success: {(response: HTTPResponse) -> Void in
println("response: \(response.responseObject!)")
},failure: {(error: NSError) -> Void in
println("error: \(error)")
})

The HTTPResponse contains all the common HTTP response data, such as the responseObject of the data and the headers of the response.

POST

A POST request is just as easy as a GET.

var request = HTTPTask()
request.POST("http://domain.com/create", parameters: ["param": "hi", "something": "else", "key": "value"], success: {(response: HTTPResponse) -> Void in
},failure: {(error: NSError) -> Void in
})

PUT

PUT works the same as post. The example also include a file upload to do a multi form request.

let fileUrl = NSURL.fileURLWithPath("/Users/dalton/Desktop/file")
var request = HTTPTask()
request.PUT("http://domain.com/1", parameters:  ["param": "hi", "something": "else", "key": "value","file": HTTPUpload(fileUrl: fileUrl)], success: {(response: HTTPResponse) -> Void in
},failure: {(error: NSError) -> Void in
})

The HTTPUpload object is use to represent files on disk or in memory file as data.

DELETE

DELETE works the same as the GET.

var request = HTTPTask()
request.DELETE("http://domain.com/1", parameters: nil, success: {(response: HTTPResponse) -> Void in
println("DELETE was successful!")
},failure: {(error: NSError) -> Void in
println("print the error: \(error)")
})

HEAD

HEAD works the same as the GET.

var request = HTTPTask()
request.HEAD("http://domain.com/image.png", parameters: nil, success: {(response: HTTPResponse) -> Void in
println("The file does exist!")
},failure: {(error: NSError) -> Void in
println("File not found: \(error)")
})

项目主页:http://www.open-open.com/lib/view/home/1409123456744

昵    称:
验证码:

相关文档: