iosswiftxcodealamofiremoya

Moya Alamofire request with no url coding


How to consume a get-API (having following request-structure) with Moya?

http://some.environment.com/some/api/some/contacts/81193?types=["details", "permissions"]

Here is what I've tried.

enum MyApiTarget: TargetType {

    case getInfo(contactID: Int, types: [String])

    public var baseURL: URL {
        switch self {
        case .getInfo:
            return URL(string: "http://some.environment.com/some/api")!
        }
    }

    public var path: String {
        switch self {
        case .getInfo(contactID: let contactId, types: _):
            return "/some/contacts/\(contactId)"
        }
    }

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

    public var sampleData: Data {
        return Data()
    }

    public var task: Task {
        switch self {
        case .getInfo(contactID: _, types: let types):
            return .requestParameters(
                 parameters: ["types" : types],
                 encoding: URLEncoding.queryString
            )
        }
    }

    public var headers: [String: String]? {
        return nil
    }

}

Above code produces following URL.

http://some.environment.com/some/api/some/contacts/81193?types%5B%5D=details&types%5B%5D=permissions

I've tried followings for encoding

None of the encoding helped me to produce expected result.


Solution

  • I solved it by putting code as follows.

    Replace task as follows.

    public var task: Task {
        switch self {
            case .getInfo(contactID: _, types: let types):
                var arrayOfTypesInString = types.joined(separator: "\", \"")
                arrayOfTypesInString = "\"\(arrayOfTypesInString)\""
                let params = ["types": "[\(arrayOfTypesInString)]"]
                return .requestParameters(
                     parameters: params,
                     encoding: URLEncoding.queryString
                )
            }
        }
    }
    

    For now, I've done manual JSON encoding. Alternate way of doing it would be, first convert data to JSON & from JSON create string & supply.