My project is in Objective-C and I'm converting it to Swift. Objective-C project uses AFNetworking
for networking. In new swift project I'm using Moya
.
I have created Moya target named PhTrackerAPI
,
public enum PhTrackerAPI {
case login
case checkNumberExist(phoneno: String, code: String)
case todos
}
extension PhTrackerAPI: TargetType {
public var baseURL: URL {
return URL(string: "http://numberfinding.com/vaghani/call2loc/Api_c2l")!
}
public var path: String {
switch self {
case .login: return "/login"
case .checkNumberExist: return "/check_number_exist"
case .todos: return "/todos"
}
}
public var method: Moya.Method {
switch self {
case .login, .checkNumberExist:
return .post
case .todos:
return .get
}
}
public var sampleData: Data {
return Data()
}
var parameters: [String: Any]? {
switch self {
case .login:
return [:]
case .checkNumberExist(let phoneno, let code):
return ["phone":phoneno,
"country_code":code]
case .todos:
return nil
}
}
public var task: Task {
switch self {
case .login, .checkNumberExist:
return .requestParameters(parameters: parameters!, encoding: JSONEncoding.default)
default: return .requestPlain
}
}
public var headers: [String: String]? {
return ["Content-Type": "application/json"]
}
// 7
public var validationType: ValidationType {
return .successCodes
}
}
When I request API from Postman, it is giving response, But If I call it via Moya
, it gives error of "Parameter not found". Why this error occurs? Anyone can help me?
EDIT:
My API wants parameters in form data. So I have updated task as below and it is works fine now.
var task: Task {
switch self {
case .checkNumberExist:
var multipartData = [MultipartFormData]()
for (key, value) in parameters! {
let formData = MultipartFormData(provider: .data("\(value)".data(using: .utf8)!), name: key)
multipartData.append(formData)
}
return .uploadMultipart(multipartData)
default: return .requestPlain
}
}