I\'m using Moya 10.0.1 and I\'m having a problem when I\'m trying to upload an image to the server.
I did follow the Multipart Upload example and this is my setup code:<
complete detail of uploading image using multipart request with Moya Swift. setp 1
import Foundation
import Moya
enum ImageService {
case updateUserAvatar(user_id: Int, cover_image: UIImage)
}
extension ImageService: TargetType {
public var baseURL: URL { return URL(string: "https://api.shoclef.com/api")! }
public var path: String {
switch self {
case .updateUserAvatar(_,_): return "/updatecoverimage"
}
}
public var method: Moya.Method {
switch self {
case .updateUserAvatar(_, _):
return .post
}
}
var task: Task {
switch self {
case .updateUserAvatar(let user_id, let cover_image):
let imageData = UIImageJPEGRepresentation(cover_image, 1.0)
let memberIdData = "\(user_id)".data(using: String.Encoding.utf8) ?? Data()
var formData: [Moya.MultipartFormData] = [Moya.MultipartFormData(provider: .data(imageData!), name: "cover_image", fileName: "asdas.png", mimeType: "image/jpeg")]
formData.append(Moya.MultipartFormData(provider: .data(memberIdData), name: "user_id"))
return .uploadMultipart(formData)
}
}
public var sampleData: Data {
return Data()
}
public var headers: [String : String]? {
switch self {
case .updateUserAvatar: return ["Content-type" : "application/json"]
}}}
step 2
@IBOutlet weak var myImage: UIImageView!
var provider = MoyaProvider()
@IBAction func uploadImage(_ sender: UIButton) {
provider.request(ImageService.updateUserAvatar(user_id: 1163, cover_image: myImage.image!)) { result in
switch result {
case .success(let response):
do {
let image = try JSONDecoder().decode(Updatecoverimage.self, from: response.data)
print(image.data)
} catch {
print(error) // This code will run because the statusCode is 500
}
case .failure(let error):
print("Failure: \(error)")
}
}
}
}
struct Updatecoverimage: Codable {
let status, data: String
}