Alamofire的強(qiáng)大應(yīng)該不用多說了,每個(gè)做iOS開發(fā)的應(yīng)該都聽過他的大名。
之前我一直混在OC之中,最近開始寫Swift,新建了一個(gè)項(xiàng)目,準(zhǔn)備搭建網(wǎng)絡(luò)層的框架,Alamofire已經(jīng)幫我們封裝好了所有的東西,也匹配的基本上全部的case。
開開心心搭建好底部請(qǐng)求層,開始寫業(yè)務(wù)代碼的時(shí)候發(fā)現(xiàn),我們這邊的圖片上傳策略是將圖片上傳到Amazon的AWS服務(wù)器。然后要求使用PUT方法帶入Content-Type = application/octet-stream。
我之前是直接使用Alamofire給封裝好的Upload方法:
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
/// for uploading the `data`.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
public func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
return SessionManager.default.upload(data, to: url, method: method, headers: headers)
}
請(qǐng)求了之后發(fā)現(xiàn)每次都是返回403.
后邊看了一下庫里的代碼,發(fā)現(xiàn)直接建立一個(gè)Request可能行得通,所以我后來直接創(chuàng)建了一個(gè)Request通過Alamofire來請(qǐng)求。
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.put.rawValue
request.setValue(“application/octet-stream”, forHTTPHeaderField: “Content-Type”)
request.httpBody = data
Alamofire.request(request).response { (afResponse) in
print(afResponse);
}
看到果然成功了。
不過這樣做也失去了upload中帶的一些特性,包括進(jìn)度、續(xù)傳等等。
這篇文章僅限自己學(xué)習(xí),最近剛開始寫swift,對(duì)swift的一些特性和Alamofire的使用還不太熟悉。不知道有沒有更好的解決辦法。如果有別的方法希望有大佬指正。