iOS开发-Alamofire上传AWS图片

2020-01-01  本文已影响0人  张囧瑞

Alamofire的强大应该不用多说了,每个做iOS开发的应该都听过他的大名。

之前我一直混在OC之中,最近开始写Swift,新建了一个项目,准备搭建网络层的框架,Alamofire已经帮我们封装好了所有的东西,也匹配的基本上全部的case。

开开心心搭建好底部请求层,开始写业务代码的时候发现,我们这边的图片上传策略是将图片上传到Amazon的AWS服务器。然后要求使用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)
}

请求了之后发现每次都是返回403.

后边看了一下库里的代码,发现直接建立一个Request可能行得通,所以我后来直接创建了一个Request通过Alamofire来请求。

        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中带的一些特性,包括进度、续传等等。

这篇文章仅限自己学习,最近刚开始写swift,对swift的一些特性和Alamofire的使用还不太熟悉。不知道有没有更好的解决办法。如果有别的方法希望有大佬指正。

上一篇 下一篇

猜你喜欢

热点阅读