swift - URL 请求的编码参数

标签 swift alamofire nsurlrequest urlrequest

我创建了一个路由器来生成 URL 请求。

enum Router: URLRequestConvertible {
    static let baseURLString = "SERVERIP"

    case GetAEDInRange(String) 
    // match URLRequest routes to Alamofire methods
    var URLRequest: NSMutableURLRequest {
        var method: Alamofire.Method {
            switch self {

            case .GetAEDInRange:
                return .GET
            }
        }

        // The output contains the path and parameters like ("aeds", newAED)
        let result: (path: String, parameters: [String: AnyObject]?) = {
            switch self {

            case .GetAEDInRange(let parameters):
                return ("aeds", parameters)
        }()

        // Generate URL Request
        let URL = NSURL(string: Router.baseURLString)!

        // Append the path components from the result
        print(result.path)
        let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path))

        // Create URLRequest inclunding the encoded parameters
        let encoding = Alamofire.ParameterEncoding.JSON
        let (encodedRequest, _) = encoding.encode(URLRequest, parameters: result.parameters)
        encodedRequest.HTTPMethod = method.rawValue
        return encodedRequest
    }
}

我期望的输出是:http://BASEURL/v1/aed?latitude=100&longitude=100

当我使用 Alamofire 发出带有附加参数的 GET 请求时,它工作正常:

    Alamofire.request(.GET, "http://SERVER/v1/aeds", parameters: parameters).responseJSON { (response) -> Void in
        print(response.result.value)
    }

当我改用我的路由器时,输出没有按预期生成:

    Alamofire.request(Router.GetAEDInRange(parameters)).responseJSON { (response) -> Void in
        print(response.result.value)
    }

当我打印 URL 字符串时,我得到:`http://SERVER/v1/aeds/ `` 我需要如何更换路由器?我以某种方式与参数组件作斗争。

最佳答案

改变这一行

let encoding = Alamofire.ParameterEncoding.JSON

为此:

let encoding = Alamofire.ParameterEncoding.URLEncodedInURL

要了解 Alamofire 中参数编码之间的区别,请查看 here .

关于swift - URL 请求的编码参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35536772/

相关文章:

iphone - ios 从 NSURLRequest 获取 header 我收到错误 [NSConcreteMutableData allHeaderFields] : unrecognized selector

ios - 如何使用返回数据的完成处理程序为方法编写单元测试?

ios - 以编程方式添加一个新的 UIView,其中包含不同的数据

ios - 如何按原样将字符串值传递给 NSString

swift - 如何在 Swift 中使用 Alamofire 将参数作为正文发送到 PUT 方法

ios - “(_, _, _) -> Void”无法转换为 'Result<Post> -> Void'

iphone - NSURLConnection 在 UITableView 滚动之前不是 "firing"

ios - Swift:使 UIGestureRecognizer 只影响一个 UICollectionViewCell 而不是所有

ios - 使用模型异步数据和 TableView

swift - Alamofire下载方法 "Use of undeclared type ´DownloadFileDestination´"