Swift 使用 Alamofire 框架上传文件

Alamofire 是一个在GitHub上star数已超过24k的网络库。

先贴出一段代码,这是我在StravaKit中增加的上传fit文件功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
extension Requestor {

public func uploadFitFile(url: String, params: [String : String]?, file: URL, completionHandler: ((_ response: Any?, _ error: NSError?) -> ())?) {

guard let accessToken = Strava.sharedInstance.accessToken
else {
let error = Strava.error(.noAccessToken, reason: "No Access Token")
completionHandler?(nil, error)
return
}
debugPrint(accessToken)
let au = "Bearer \(accessToken)"
let headers = ["Authorization": au]


Alamofire.upload(multipartFormData: { (multipartFormData) in
if let params = params {
for (key, value) in params {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
}
multipartFormData.append(file, withName: "file", fileName: file.lastPathComponent, mimeType: "multipart/form-data")
}, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: baseUrl + url, method: .post, headers: headers) { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON(completionHandler: { (response) in

if let value = response.result.value {
let dict = value as! Dictionary<String, Any>;
var error = response.result.error as NSError?
if let err = dict["error"] {
if (err as AnyObject).isKind(of: NSNull.self) {
// 成功
debugPrint("成功")

} else {
// 失败
debugPrint("失败",err)
error = NSError.init(domain: "strava", code: 0, userInfo: [NSLocalizedDescriptionKey:err])

}

}

if let completionHandler = completionHandler {
completionHandler(response.result,error)
}
} else {
if let completionHandler = completionHandler {
if let error = response.result.error {
completionHandler(response.result,error as NSError)
}

}

}

})
case .failure(let error):
print(error)
}

}

}


}