Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload with alamofire Router

How can i upload a file with the alamofire Router? Struggling with it.

I'm also interested how i can upload file and parameters in the same request with Alamofire router.

Thanks!

like image 912
Ludvig Avatar asked Oct 16 '14 19:10

Ludvig


1 Answers

I upload an image using the following code. For a given file type, you should be able to adjust the multipartEncoding block accordingly.

let json: [String : Any] = ["key", "value"]

let image = UIImage(named: "Something")!

guard let imageData = UIImagePNGRepresentation(image) else {
    // We couldn't convert the image into data :(
}

let multipartEncoding: (MultipartFormData) -> Void = { multipartFormData in
    multipartFormData.append(imageData, withName: "image", fileName: "image.png", mimeType: "image/png")
}

let request = Router.uploadPicture(parameters: json) // This is just a plain POST

sessionManager.upload(
    multipartFormData: multipartEncoding,
    with: request,
    encodingCompletion: { (encodingResult) in
        switch encodingResult {
        case .success(let request, _, _):
            request.validate().responseJSON(completionHandler: { (dataResponse) in
                if let error = dataResponse.result.error {
                    // Network request failed :(
                }
                // SUCCESS!
            })
        case .failure(_):
            // Couldn't encode the image :(
        }
})

This is assuming your Router looks something like this.

enum Router: URLRequestConvertible {

    case uploadPicture(parameters: Parameters)

    static var baseUrl = "https://website.com/"

    var method: HTTPMethod {
        switch self {
        case .uploadPicture(_):
            return .post
        }
    }

    var path: String {
        switch self {
        case .uploadPicture(_):
            return "api/upload-picture/"
        }
    }

    // MARK: - URLRequestConvertible

    func asURLRequest() throws -> URLRequest {

        let url = try Router.baseUrl.asURL().appendingPathComponent(path)
        var urlRequest = try URLRequest(url: url, method: method)
        var encodedUrlRequest: URLRequest?

        switch self {

        case .uploadPicture(let parameters):
            encodedUrlRequest = try? JSONEncoding.default.encode(urlRequest, with: parameters)

        }

        return encodedUrlRequest ?? urlRequest
    }
}
like image 182
Mike Cole Avatar answered Nov 15 '22 03:11

Mike Cole