我正在为我正在处理的项目(iOS,Swift 3,Alamofire)设置网络层,并且我一直在使用Alamofire的文档。
在使用从URLRequestConvertible扩展的路由器枚举时,在决定如何添加多部分请求时,我需要帮助。在Alamofire文档中,它解释了如何执行多部分请求,但它的实现方式似乎与它们的Routers和URLRequestConvertible协议的实现非常吻合。
这是他们如何进行分段上传:
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(unicornImageURL, withName: "unicorn")
multipartFormData.append(rainbowImageURL, withName: "rainbow")
},
to: "https://httpbin.org/post",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
这是我一直关注的路由器的基本实现:
import Alamofire
enum Router: URLRequestConvertible {
//Different cases go here:
case example
var method: HTTPMethod {
switch self {
default:
return .get
}
}
static let basePath = "http://example.com"
var path: String {
switch self {
default:
return ""
}
}
func asURLRequest() throws -> URLRequest {
let url = try Router.basePath.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
//Add needed headers here
switch self {
default:
break
}
// If URL has params, add them here
switch self {
default:
break
}
return urlRequest
}
}
有人能指出我如何将两者结合起来的正确方向吗?
答案 0 :(得分:1)
Alamofire有一个多部分上传API,以URLRequestConvertible
为参数。从上面的例子中可以看出:
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(unicornImageURL, withName: "unicorn")
multipartFormData.append(rainbowImageURL, withName: "rainbow")
},
with: Router.example,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
})