Search code examples
stringreplacerequestalamofireswift4

replacing %3F instead of `?` in url


i have this problem when i want call this method in request. It seems to be replacing %3f instead of ? in swift4

its my ApiRouter

struct ApiRouter {
enum Router: URLRequestConvertible {

   case getAllPlcae(id: Int, paseSize: Int, pageNumber: Int, countryID: Int, cityID: Int)

    var method: Alamofire.HTTPMethod {
        switch self {

       case .getAllPlcae:
            return .get

        }
    }

    func asURLRequest() throws -> URLRequest {
        let result: (path: String, parameters: [String: AnyObject]?) = {
            switch self {

            case .getAllPlcae(let id, let pageSize, let pageNumber, let countryID, let cityID):
                return("Location?textToSearch=&tagIds=&id=\(id)&pageSize=\(pageSize)&pageNumber=\(pageNumber)&countryID=\(countryID)&cityID=\(cityID)",nil)

            }
        }()


        // MARK: - Set HTTP Header Field
        let url = URL(string: Constants.ApiConstants.baseURLString)!
        var urlRequest = URLRequest(url: url.appendingPathComponent(result.path))
        urlRequest.httpMethod = method.rawValue
        if let token = User.getToken() {
            urlRequest.setValue(token, forHTTPHeaderField: "Authorization")
        }
        let encoding = try Alamofire.URLEncoding.default.encode(urlRequest, with: result.parameters)

        return encoding
    }
}}

when i call this request , just like down

Alamofire.request(ApiRouter.Router.getAllPlcae(id: 0, paseSize: 10, pageNumber: 1, countryID: 0, cityID: 0)).responseArray { (response: DataResponse<[Place]>) in }

its my url request

Location%3FtextToSearch=&tagIds=&id=0&pageSize=10&pageNumber=1&countryID=0&cityID=0

It seems to be replacing %3f instead of ?

how can fix it ?


Solution

  • I found the solution for this question. We should remove Percent Encoding.

            // MARK: - Set HTTP Header Field
            let base = URL(string: Constants.ApiConstants.baseURLString)!
            let baseAppend = base.appendingPathComponent(result.path).absoluteString.removingPercentEncoding
            let url = URL(string: baseAppend!)
            var urlRequest = URLRequest(url: url!)
            urlRequest.httpMethod = method.rawValue
            if let token = User.getToken() {
                urlRequest.setValue(token, forHTTPHeaderField: "Authorization")
            }
            let encoding = try Alamofire.URLEncoding.default.encode(urlRequest, with: result.parameters)
    
            return encoding