Alamofire编码问题

时间:2017-07-11 15:26:06

标签: ios swift alamofire

使用Alamofire创建路由器来处理我的API请求,如下所示:

enum GoogleRouter: URLRequestConvertible {

case FetchCoordinatesFromPostcode(postcode: String)

static let baseURLString = "https://maps.googleapis.com/maps/api/geocode/json?"

var method: HTTPMethod {
    switch self {
    case .FetchCoordinatesFromPostcode:
        return .get
    }
}

var path: String {
    switch self {
    case .FetchCoordinatesFromPostcode(let postcode):
        return "?address=\(postcode)&key=MY_KEY"
    }
}

func asURLRequest() throws -> URLRequest {
    let url = try GoogleRouter.baseURLString.asURL()
    print(url)
    var urlRequest = URLRequest(url: url.appendingPathComponent(path))
    urlRequest.httpMethod = method.rawValue

    switch self {
    default:
        break
    }

    return urlRequest
}

}

问题是,从我输入的邮政编码中获取lat长度的URL在URL的中间有一个?。无论我在哪里放置问号,无论是baseURLString的末尾还是path的开头,?似乎都会成为编码因此向错误发送请求url(我已经在上面的代码中插入了)

我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

尝试这样

enum GoogleRouter: URLRequestConvertible {

//the base url (REMOVE THE ? MARK)
static let baseURLString = "https://maps.googleapis.com/maps/api/geocode/json"

//the router
case FetchCoordinatesFromPostcode([String:Any])  //set the case like this

var method: HTTPMethod {
    switch self {
    case .FetchCoordinatesFromPostcode:
        return .get
    }
}

//WE Won't be needing path, so lets just remove it

/*var path: String {
    switch self {
    case .FetchCoordinatesFromPostcode(let postcode):
        return "?address=\(postcode)&key=MY_KEY"
    }
}*/

func asURLRequest() throws -> URLRequest {
    //get the url from string
    let url = try GoogleRouter.baseURLString.asURL()

    //prepare urlrequest
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = method.rawValue

    switch self {
    case .FetchCoordinatesFromPostcode(let parameters):
        urlRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters)
    }

    return urlRequest
}

}

func testCall() {
let parameters = ["addres":"myAddress","key":"MY_KEY"]
let request = Alamofire.request(GoogleRouter.FetchCoordinatesFromPostcode(parameters))
request.validate().responseJSON { (response) in
    //Do The Thing
}

}