Moya更改URL

时间:2017-05-29 11:59:42

标签: ios swift google-places-api google-maps-sdk-ios moya

我尝试使用Google Places拨打Moya Api,但网址有问题。 Maya更改了我的网址中的字符。在这种情况下,例如在字符?添加%3f并更改, %2C之前。当我将此地址复制并粘贴到我的网络浏览器中时,收到错误,但当我删除%3f并更改%2C ,时,我会收到正确的答案表单API。如果我不想在我的网址中更改此字符,我应该在Moya中设置什么内容?

我的Moya提供商看起来像这样:

extension GooglePlacesService: TargetType {

var baseURL: URL {
    return URL(string: "https://maps.googleapis.com")!
}

var path: String {
    switch self {
    case .gasStation:
        return "/maps/api/place/nearbysearch/json?"
    }
}

var parameters: [String : Any]? {
    switch self {
    case .gasStation(let lat, let long, let type):
        return ["location": "\(lat),\(long)", "type" : "gas_station", "rankby" : "distance", "keyword" : "\(type)", "key" : GoogleKeys.googlePlacesKey]
    }
}

var parameterEncoding: ParameterEncoding {
    switch self {
    case .gasStation:
        return URLEncoding.queryString
    }
}

var method: Moya.Method {
    switch self {
    case .gasStation:
        return .get
    }
}

var sampleData: Data {
    switch self {
    case .gasStation:
        return "".utf8Encoded
    }
}

var task: Task {
    switch self {
    case .gasStation:
        return .request
    }
  }
}


private extension String {
var urlEscaped: String {
    return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}

var utf8Encoded: Data {
    return self.data(using: .utf8)!
  }
}

生成Moya的URL看起来像那样(不能使用API​​):

https://maps.googleapis.com/maps/api/place/nearbysearch/json%3F?key=MYAPIKEY&keyword=XXXXXX&location=51.0910166687869%2C17.0157277622482&rankby=distance&type=gas_station

适用于API的网址:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=MYAPIKEY&keyword=XXXXXX&location=51.0910166687869,17.0157277622482&rankby=distance&type=gas_station

1 个答案:

答案 0 :(得分:0)

我对“?”也有同样的问题被转换为'%3F': enter image description here

解决方案是使路径中没有棘手的符号(例如“?”,“,”),并使用 URLEncoding.default 将其放入Moya设置的 var Task 中。 >相反: enter image description here enter image description here