SwiftHTTP的使用(译)

SwiftHttp是是一种轻便型的NSURLSession网络请求封装,可以让你的HTTP请求更加简明快捷.

项目地址:https://github.com/daltoniam/SwiftHTTP


GET:

最基本的请求。默认情况下,将返回一个NSData对象的response。

do {
    let opt = try HTTP.GET("https://google.com")
    opt.start { response in
        if let err = response.error {
            print("error: \(err.localizedDescription)")
            return //also notify app of failure as needed
        }
        print("opt finished: \(response.description)")
        //print("data is: \(response.data)") access the response of the data with response.data
    }
} catch let error {
    print("got an error creating the request: \(error)")
}



我们还可以为其添加参数,他们会正确地序列化到各自的HTTP请求中。

do {
    //the url sent will be https://google.com?hello=world¶m2=value2
    let opt = try HTTP.GET("https://google.com", parameters: ["hello": "world", "param2": "value2"])
    opt.start { response in
        if let err = response.error {
            print("error: \(err.localizedDescription)")
            return //also notify app of failure as needed
        }
        print("opt finished: \(response.description)")
    }
} catch let error {
    print("got an error creating the request: \(error)")
}


HttpResponse包含了所有基本的HTTP响应数据,如response返回数据和response返回头。

Post

let params = ["param": "param1", "array": ["first array element","second","third"], "num": 23, "dict": ["someKey": "someVal"]]
do {
    let opt = try HTTP.POST("https://domain.com/new", parameters: params)
    opt.start { response in
    //do things...
    }
} catch let error {
    print("got an error creating the request: \(error)")
}


Json RequestSerializer

请求参数也可以被序列化为JSON类型。默认情况下,使用标准的HTTP请求序列化形式编码。

do {
    let opt = try HTTP.New("https://google.com", method: .GET, requestSerializer: JSONParameterSerializer())
    opt.onFinish = { response in
        if let err = response.error {
            print("error: \(err.localizedDescription)")
            return //also notify app of failure as needed
        }
        print("opt finished: \(response.description)")
    }
} catch let error {
    print("got an error creating the request: \(error)")
}


Operation Queue

SwiftHTTP也支持队列操作

let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 2
do {
    let opt = try HTTP.New("https://google.com", method: .GET)
    opt.onFinish = { response in
    //do stuff
    }
    operationQueue.addOperation(opt)
} catch let error {
    print("got an error creating the request: \(error)")
}


Cancel

如果你稍后想取消这个请求,那么你可以调用其取消方法

opt.cancel()


Progress

SwiftHTTP也可以监控一个请求的进度.

do {
    let opt = try HTTP.GET("https://domain.com/somefile")
    opt.progress = { progress in
        print("progress: \(progress)") //this will be between 0 and 1.
    }
    opt.start { response in
    //do stuff
    }
} catch let error {
    print("got an error creating the request: \(error)")
}


Global handlers

SwiftHTTP也可以进行全局处理,减少重复的HTTP请求修改,如确定的报头或设置NSMutableURLRequest性质如timeoutinterval(超时设置)。

//modify NSMutableURLRequest for any Factory method call (e.g. HTTP.GET, HTTP.POST, HTTP.New, etc).
HTTP.globalRequest { req in
    req.timeoutInterval = 5
}

//set a global SSL pinning setting
HTTP.globalSecurity(HTTPSecurity()) //see the SSL section for more info

//set global auth handler. See the Auth section for more info
HTTP.globalAuth { challenge in
    return NSURLCredential(user: "user", password: "passwd", persistence: .ForSession)
}


//

由于能力所限,就自己理解进行了翻译,有很多不周到之处请指正,文章中还有一部分是笔者尚未涉及到的内容,不敢贸然翻译,只当抛砖引玉.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值