我正在尝试将功能添加到允许用户将跑步上传到他们的 Strava 个人资料的应用程序中。目前,运行以 gpx 文件的形式存储在应用程序的 Documents 目录中,虽然我知道如何访问它们,但我在使用 Alamofire 请求的语法时遇到了问题。我的代码如下所示:
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)
}
})
}
我收到了与 Postman 合作的请求,但没有与 Alamofire 合作。这是与 Postman 成功请求的照片:https ://i.stack.imgur.com/oxQcx.png
使用 Alamofire,我每次都会获得 400 状态,结果如下:
[Data]: 88 bytes
[Result]: SUCCESS: {
errors = (
{
code = empty;
field = data;
resource = Upload;
}
);
message = "Bad Request";
}
header 页面下的一个元素是授权令牌,与 Alamofire 请求中的那个相同。任何帮助深表感谢。