Swift 的 HTTP 開發包:SwiftHTTP

jopen 10年前發布 | 78K 次閱讀 SwiftHTTP Apple Swift開發

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.baiduhome.net/lib/view/home/1409123456744

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!