2

I'm trying to add functionality into an app that would allow a user to upload runs to their Strava profile. Currently the runs are stored in the Documents directory of the app as gpx files, and although I know how to access them, I'm having trouble with the syntax of the Alamofire request. My code looks like this:

func getDocumentsDirectory() -> URL {
  let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
  let documentsDirectory = paths[0]
  do {
    let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)
    print("Directory contents: \(fileURLs)")
  } catch {
    print("Error while enumerating files \(documentsDirectory.path): \(error.localizedDescription)")
  }
  return documentsDirectory
}

var path = getDocumentsDirectory()
path = path.appendingPathComponent("Sample_Activity.gpx")
print("\nPath component points to: \(path)\n")

/* ======================== Begin Strava API Upload =========================== */


Alamofire.upload(multipartFormData:{ multipartFormData in

  multipartFormData.append("run".data(using: String.Encoding.utf8)!, withName: "activity_type")
  multipartFormData.append(path, withName:"activity")
  multipartFormData.append("gpx".data(using: String.Encoding.utf8)!, withName: "data_type")
        },
           usingThreshold:UInt64.init(),
           to:"https://www.strava.com/api/v3/uploads",
           method:.post,
           headers:["Authorization": "Bearer <token>"],
             encodingCompletion: { encodingResult in
               switch encodingResult {
               case .success(let upload, _, _):
                 upload.responseJSON { response in
                   debugPrint(response)
                 }
               case .failure(let encodingError):
                 print(encodingError)
               }
        })

    }

I got the request to work with Postman, but not with Alamofire. Here is a photo of the successful request with Postman: https://i.stack.imgur.com/oxQcx.png

With Alamofire, I get a 400 status every time with the following result:

[Data]: 88 bytes
[Result]: SUCCESS: {
    errors =     (
                {
            code = empty;
            field = data;
            resource = Upload;
        }
    );
    message = "Bad Request";
}

The one element under the header page is the authorization token, which is the same as the one in the Alamofire request. Any help is much appreciated.

Izak
  • 21
  • 3
  • 1
    This was a very easy fix, I changed multipartFormData.append(path, withName:"activity") to multipartFormData.append(path, withName:"file") – Izak May 16 '19 at 17:40
  • How did you create .gpx file from the workout data? – Mudassir Oct 20 '22 at 11:04
  • I found solution how to create gpx file in different topic: https://stackoverflow.com/a/47861142/1808733 – Arijan Feb 10 '23 at 20:58

0 Answers0