Trying to upload image to server but didn't succeed, here is my code, nothing happened, couldn't figure why. What could be wrong?
import Foundation
extension URLRequest {
mutating func setMultipartFormDataBody(params: [String: (Data?, filename: String?)]) {
let boundary = UUID().uuidString
self.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = Data()
for (key, (data, filename)) in params {
body.append("--\(boundary)\r\n")
if let filename = filename {
body.append("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n")
}
else {
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n")
}
body.append("\r\n")
body.append(data ?? Data())
body.append("\r\n")
}
body.append("--\(boundary)--")
self.httpBody = body
}
}
extension Data {
mutating func append(_ s: String) {
self.append(s.data(using: .utf8)!)
}
}
thats even not posting string to server added request task but the body ignored, must set the boundry and low level? URLSESSEION is not like ALAMOFIRE?
let boundary = "Boundary-\(UUID().uuidString)"
var request = URLRequest(url: URL(string: "url")!)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = httpBody as Data
URLSession.shared.dataTask(with: request) { data, response, error in
// handle the response here
}.resume()