我正在为我正在研究的项目(iOS,Swift 3,Alamofire)设置网络层,并且我一直在使用Alamofire的文档来这样做。

在决定如何使用从URLRequestConvertible扩展的Router枚举时,如何添加多部分请求时需要帮助。在Alamofire文档中,它说明了如何执行多部分请求,但处理方式似乎与路由器和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
    }
}

有人能指出我正确的方向,将两者结合吗?

最佳答案

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)
        }
    })

08-15 20:48