swiftaudiomultipartform-dataurlsessionm4a

How to send audio file in Multipart form data using URLSession? Swift


I want to send an audio file which is in the format of .m4a in multipart from data using URLSession. Currently, I am successful in sending the audio file to server, but at the server end, my audio file is not being recognized as an audio file, and that's because my extension .m4a is not reaching there. On my end, I checked all possibilities, like checking mime type 'audio/m4a', my audio URL ending with the extension m4a. But I am unable to get to the problem. Below is the code I am using to send audio. Any help would be appreciated.

guard let url = URL(string: "myURL") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = generateBoundary()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
let audioMedia = AudioMedia(audioWithURL: audioURL, forKey: "myKey")
let dataBody = createDataBody(withParameters: parameters,audio: audioMedia, boundary: boundary)
request.httpBody = dataBody
     
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
     if let data = data {
        do {
             let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String]
                if let res = json?["res"] {
                      completion(.success(data))
                    }
                }
             } catch {
                 print(error)
                 completion(.failure(.jsonError))
             }
         }
        if let error = error {
            print(error.localizedDescription)
            completion(.failure(.unknownError))
        }
    }.resume()
 }

AudioMedia

struct AudioMedia {
let key: String
let audioURL : URL
let mimeType: String

init?(audioWithURL url: URL, forKey key: String) {
    self.key = key
    self.mimeType = "audio/m4a"
    self.audioURL = url
  }
}

Solution

  • The problem is that you aren't including a filename (including the important filetype) in your request. Try putting this string in immediately after the starting boundary and before your audio data:

    "Content-Disposition:form-data; name=\"audiofile"; filename=\"audio.m4a\"\r\n\r\n"