2017-04-03 58 views
0

我正在通過此格式發送請求,以使用參數發出請求。但是,我將如何使用此參數將圖像作爲多部分主體發送?如何使圖像Alamofire放置請求參數?

class APIManager: NSObject { 
    enum Router: URLRequestConvertible { 

     static var baseURLString = baseURLString 
     static let xSource = X_SOURCE_HEADER 

     case updateProfile([String: AnyObject]) 

     var method: HTTPMethod { 
      switch self { 
      case .updateProfile: 
       return .put 
      } 
     } 

     var path: String { 
      switch self { 
      case .updateStockShelfUnits: 
       return profile_url 
      } 
     } 
     func asURLRequest() throws -> URLRequest { 
      let url = try GlobalData.gBaseURLString.asURL() 
      var urlRequest = URLRequest(url: url.appendingPathComponent(path)) 
      urlRequest.httpMethod = method.rawValue 

      switch self { 

      case .updateProfile(let parameters): 
       urlRequest.setValue(access_token, forHTTPHeaderField: "X-User-Token") 
       urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) 
      } 
      return urlRequest 
     } 
    } 

    func makeRequestToUpdateProfile(param: [String : AnyObject], img: UIImage, completion: @escaping completionHandlerWithSuccessAndErrorMessage) { 

     Alamofire.request(Router.updateprofile(param)) .responseJSON { response in 
      switch response.result { 
      case .success(let JSON): 
       print(JSON) 
       completion(true, "Success") 
      case .failure(let Error): 
       print("Request failed with error: \(Error)") 
       completion(false, Error.localizedDescription) 
      } 
     } 
    } 
} 

在這裏,我會做什麼,使圖像作爲多部分身體請求參數?請求只有參數運行良好的API。

通過 斯威夫特3Alamofire 4

// import Alamofire 
func uploadWithAlamofire() { 
    let image = UIImage(named: "bodrum")! 

    // define parameters 
    let parameters = [ 
    "hometown": "yalikavak", 
    "living": "istanbul" 
    ] 

    Alamofire.upload(multipartFormData: { multipartFormData in 
    if let imageData = UIImageJPEGRepresentation(image, 1) { 
     multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png") 
    } 

    for (key, value) in parameters { 
     multipartFormData.append((value?.data(using: .utf8))!, withName: key) 
    }}, to: "upload_url", method: .post, headers: ["Authorization": "auth_token"], 
     encodingCompletion: { encodingResult in 
      switch encodingResult { 
      case .success(let upload, _, _): 
      upload.response { [weak self] response in 
       guard let strongSelf = self else { 
       return 
       } 
       debugPrint(response) 
      } 
      case .failure(let encodingError): 
      print("error:\(encodingError)") 
      } 
    }) 
} 

信用

回答