How to do multipart/form-data post request with Swift?
13,532
Swift 3, Try this, Remove responseHandler parameter and any other if not use in your code
class func API_POST_FORM_DATA(param:[String : String], songData:Data?, fileName:String ,responseHandler : @escaping CompletionHandler)
{
let API_URL = API_POST_ADD_SONG_TO_PLAYLIST
print("API_URL : \(API_URL)")
let request = NSMutableURLRequest(url: URL(string: API_URL)!)
request.httpMethod = "POST"
let boundary = API_Calling.generateBoundaryString()
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
let fname = fileName
let mimetype = "image/png"
//define the data post parameter
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("hi\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
if let songRawData = songData
{
body.append("Content-Disposition:form-data; name=\"song\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
body.append(songRawData)
}
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
for (key, value) in param
{
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
}
request.httpBody = body as Data
// return body as Data
print("Fire....")
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
print("Complete")
if error != nil
{
print("error upload : \(error)")
responseHandler(nil)
return
}
do
{
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
responseHandler(json as NSDictionary?)
}else
{
print("Invalid Json")
}
}
catch
{
print("Some Error")
responseHandler(nil)
}
}
task.resume()
}
class func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
Related videos on Youtube
Author by
Rayen Kamta
Updated on June 04, 2022Comments
-
Rayen Kamta almost 2 years
let Url = String(format: "http://url/ios.php") guard let serviceUrl = URL(string: Url) else { return } let parameterDictionary :[String:String] = ["Episodes" : "http://url/anime/07-ghost.html"] var request = URLRequest(url: serviceUrl) request.httpMethod = "POST" request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type") request.httpBody = NSKeyedArchiver.archivedData(withRootObject: parameterDictionary) let session = URLSession.shared session.dataTask(with: request) { (data, response, error) in if let response = response { print(response) } if let data = data { do { let json = try JSONSerialization.jsonObject(with: data, options: []) print(json) }catch { print(error) } } }.resume() }
I get error
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
not sure if im sending data correctly, i think im setting httpbody incorectly
i even tried with json request.setValue("application/json", forHTTPHeaderField: "Content-Type") guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else { return }
-
algrid over 6 yearsYou can use AFNetworking - stackoverflow.com/questions/34938242/…
-
anjnkmr over 6 yearsWhy don't you try
Alamofire
Is there any particular reason It is very easy to use github.com/Alamofire/Alamofire -
Rayen Kamta over 6 yearsfigured it out request.httpMethod = "POST" + let postString = "Episodes=" + (animeModel?.link)!; Add a comment to this line + request.httpBody = postString.data(using: String.Encoding.utf8);
-