Skip to content

Instantly share code, notes, and snippets.

@feveral
Last active October 20, 2020 15:39
Show Gist options
  • Save feveral/5f305f86b95c1ca4f84c448d7dc5d008 to your computer and use it in GitHub Desktop.
Save feveral/5f305f86b95c1ca4f84c448d7dc5d008 to your computer and use it in GitHub Desktop.
ImageUpload.swift
class MImage: Codable {
/*
if your response json like:
{
"id": "5f6c2b39f1966ce3d67f52a7",
"url": "https://storage.googleapis.com/meme-image-dev/oESZ3bm36kHibV37whWofy.jpg",
"thumbnail_url": "https://storage.googleapis.com/meme-image-dev/iofTbsJis81RTTHgBKCG43.jpg",
"usage": 1,
"created_at": "2020-09-24T05:14:33.295Z"
}
*/
var id: String
var url: String
var thumbnailUrl: String
var createdAt: String
var usage: Int
enum CodingKeys: String, CodingKey {
case id
case url
case thumbnailUrl
case createdAt
case usage
}
}
static func upload(imageData: Data, completion: @escaping (MImage) -> ()) {
let decoder: JSONDecoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
AF.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "image", fileName: "file.gif", mimeType: "image/gif")
}, to: "your_http_api_url_enpoint")
.responseDecodable(of: MImage.self, decoder: decoder) { response in
guard let value = response.value else {return}
completion(value)
}
}
// usage
upload(imageData: imageData) { mimage in
// process your mimage model
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment