Google Drive resumable upload


I’m try to upload photo to Google Drive using Alamofire.
I follow this official documentation.

I write this code:

let url = ""
    let headers = [
        "Authorization": "Bearer \(accessToken)",
        "Content-Type": "application/json; charset=UTF-8",
        "X-Upload-Content-Type": "image/png",
        "X-Upload-Content-Length": "\(file.count)"

    let params: [String: Any] = [
        "name": "MyTestFileName",
        "description": "This is test description"

    let urlRequest = try! URLRequest(url: url, method: .post, headers: headers)
    var encodedURLRequest = try! JSONEncoding.default.encode(urlRequest, with: params)
    encodedURLRequest.setValue("\(encodedURLRequest.httpBody!.count)", forHTTPHeaderField: "Content-Length")

    Alamofire.upload(file, with: encodedURLRequest)
        .uploadProgress() { progress in
            let roundedProgress = round(progress.fractionCompleted * 100)
            print("upload progress = \(Int(roundedProgress))")
        .responseJSON { response in
            print("upload completed\n\(response)\n\n")
            print("=====REQUEST INFO:\n\(String(describing: response.request))\n\n")
            //let bodyJson = try! JSONSerialization.jsonObject(with: response.request!.httpBody!, options: []) as? [String : Any]
            print("=====REQUEST BODY:\n\(String(data: response.request!.httpBody!, encoding: .utf8) ?? "nil")\n\n")
            print("=====REQUEST HEADERS:\n\(String(describing: response.request!.allHTTPHeaderFields))\n\n")

But i get error: 400 Parse Error.

According documentation, I need to add metadata JSON to request body:

“If you have metadata for the file, add the metadata to the request body in JSON format. Otherwise, leave the request body empty. The following example shows how to initiate a resumable session to upload a new file:”

Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: image/jpeg
X-Upload-Content-Length: 2000000

  "name": "myObject"

How can i do it, using Alamofire?

(I can’t use Google SDK, because Google SDK doesn’t work with App Extension. I use Resumable upload, because i need to upload image more than 5mb)


Have you attempted capturing the request of a working sample app and compare it to yours?


Add a Comment