2014-10-16 73 views

回答

0

我使用以下代碼上傳圖片。對於給定的文件類型,您應該可以相應地調整multipartEncoding塊。

let json: [String : Any] = ["key", "value"] 

let image = UIImage(named: "Something")! 

guard let imageData = UIImagePNGRepresentation(image) else { 
    // We couldn't convert the image into data :(
} 

let multipartEncoding: (MultipartFormData) -> Void = { multipartFormData in 
    multipartFormData.append(imageData, withName: "image", fileName: "image.png", mimeType: "image/png") 
} 

let request = Router.uploadPicture(parameters: json) // This is just a plain POST 

sessionManager.upload(
    multipartFormData: multipartEncoding, 
    with: request, 
    encodingCompletion: { (encodingResult) in 
     switch encodingResult { 
     case .success(let request, _, _): 
      request.validate().responseJSON(completionHandler: { (dataResponse) in 
       if let error = dataResponse.result.error { 
        // Network request failed :(
       } 
       // SUCCESS! 
      }) 
     case .failure(_): 
      // Couldn't encode the image :(
     } 
}) 

這是假設你的Router看起來像這樣。

enum Router: URLRequestConvertible { 

    case uploadPicture(parameters: Parameters) 

    static var baseUrl = "https://website.com/" 

    var method: HTTPMethod { 
     switch self { 
     case .uploadPicture(_): 
      return .post 
     } 
    } 

    var path: String { 
     switch self { 
     case .uploadPicture(_): 
      return "api/upload-picture/" 
     } 
    } 

    // MARK: - URLRequestConvertible 

    func asURLRequest() throws -> URLRequest { 

     let url = try Router.baseUrl.asURL().appendingPathComponent(path) 
     var urlRequest = try URLRequest(url: url, method: method) 
     var encodedUrlRequest: URLRequest? 

     switch self { 

     case .uploadPicture(let parameters): 
      encodedUrlRequest = try? JSONEncoding.default.encode(urlRequest, with: parameters) 

     } 

     return encodedUrlRequest ?? urlRequest 
    } 
}