Simple iOS Network Call using Moya

January 03, 2019

Install

pod 'Moya', '~> 12.0'`

Setup

enum MyService {
    case zen
}
extension MyService: TargetType {
    var baseURL: URL { return URL(string: "https://api.myservice.com")! }
    var path: String {
        switch self {
        case .zen:
            return "/zen"
        }
    }
    var method: Moya.Method {
        switch self {
        case .zen:
            return .get
        }
    }
    var task: Task {
        switch self {
        case .zen: // Send no parameters
            return .requestPlain
        }
    }
    var sampleData: Data {
        switch self {
        case .zen:
            return "Half measures are as bad as nothing at all.".utf8Encoded
        }
    }
    var headers: [String: String]? {
        return ["Content-type": "application/json"]
    }
}

Lift off!

let provider = MoyaProvider<MyService>()
provider.request(.zen) { result in
    switch result {
    case let .success(moyaResponse):
        let data = moyaResponse.data // Data, your JSON response is probably in here!
        let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etc

        // do something in your app
    case let .failure(error):
        // TODO: handle the error == best. comment. ever.
    }
}