What's the best way to set up a multipart request when extending from URLRequestConvertible

Viewed 686

I'm setting up the networking layer for a project I'm working on (iOS, Swift 3, Alamofire), and I've been using Alamofire's documentation to do so.

I need help when deciding how to add a multipart request when using the Router enums that extend from URLRequestConvertible. In the Alamofire documentation, it explains how to do a multipart request, but the way it does it doesn't seem to fit quite well with their implementation of Routers and URLRequestConvertible protocol.

This is how they do Multipart uploads:

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(unicornImageURL, withName: "unicorn")
        multipartFormData.append(rainbowImageURL, withName: "rainbow")
    },
    to: "https://httpbin.org/post",
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

And this is the basic implementation of a router that I've been following:

import Alamofire

enum Router: URLRequestConvertible {

    //Different cases go here:
    case example

    var method: HTTPMethod {

        switch self {
        default:
            return .get
        }
    }

    static let basePath = "http://example.com"

    var path: String {

        switch self {
        default:
            return ""
        }
    }

    func asURLRequest() throws -> URLRequest {
        let url = try Router.basePath.asURL()

        var urlRequest = URLRequest(url: url.appendingPathComponent(path))
        urlRequest.httpMethod = method.rawValue

        //Add needed headers here
        switch self {
        default:
            break
        }

        // If URL has params, add them here
        switch self {
        default:
            break
        }

        return urlRequest
    }
}

Can someone point me in the right direction as to how to combine the two?

1 Answers
Related