How to upload a run to a Strava athlete's profile using Alamofire

蓝咒 提交于 2021-02-08 05:38:16

问题


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.

来源:https://stackoverflow.com/questions/56161869/how-to-upload-a-run-to-a-strava-athletes-profile-using-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!