自定义标题 - Alamofire + Swift 3

时间:2016-09-04 08:25:09

标签: swift alamofire

我在尝试使用此代码时遇到错误:

func getRawJSON(method: String, paramether: String) {
    let publicKey = "publicKeyHere"
    let secretKey = "secretKeyHere
    let APIURL = "https://www.bitmarket.pl/api2/"
    let time = String(Int(NSDate().timeIntervalSince1970))

    let query = NSURLComponents()
    query.queryItems = [NSURLQueryItem(name: "method", value: method) as URLQueryItem,
                        NSURLQueryItem(name: "tonce", value: time) as URLQueryItem]

    let requestString = query.query!
    let requestData = Array(requestString.utf8)

    let params = [
        "method": method,
        "tonce:": time
        ]

    let hmac: Array<UInt8> = try! HMAC(key: secretKey.utf8.map({$0}), variant: .sha512).authenticate(requestData)

    let hmacString = hmac.map{String(format: "%02X", $0)}.joined(separator: "").lowercased()

    let URL = NSURL(string: APIURL)!
    let mutableURLRequest = NSMutableURLRequest(url: URL as URL)
    mutableURLRequest.httpMethod = "POST"

    do {
        mutableURLRequest.httpBody = try JSONSerialization.data(withJSONObject: paramether, options: JSONSerialization.WritingOptions())
    } catch {
    }

    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    mutableURLRequest.setValue(publicKey, forHTTPHeaderField: "API-Key")
    mutableURLRequest.setValue(hmacString, forHTTPHeaderField: "API-Hash")

    Alamofire.request(mutableURLRequest) //Here is a problem

}

这是错误:

Argument type 'NSMutableURLRequest' does not conform to expected type 'URLRequestConvertible'

我做错了什么? Alamofire文档说NSMutableURLRequest可以符合URLRequestConvertible。

1 个答案:

答案 0 :(得分:2)

Swift 3定义了符合协议 URLRequestConvertible 的URLRequest。您应该使用URLRequest而不是 NSMutableURLRequest

请参阅此discussion.