0

I want to upload some user data for register new users and I want to upload a profile picture. I'v tried with this code but it doesn't work, on my backend im just receiving a request with nothing like a form-data inside.

This is my swift code

func UserRegisterRequest(firstname: String, lastname: String, username: String, email: String, password: String, image: UIImage , completionHandler: @escaping (ReturnMessage) -> Void) {
    
    let parameters = ["name": "MyTestFile123321",
                      "id": "12345"]
    
    // MARK: URL Components
    var components = URLComponents()
    components.scheme = "https"
    components.host = "my-url"
    components.path = "/register"
    
    
    //MARK: Create URL
    guard let url = components.url else {
        print("Invalid URL")
        return
    }
    
    guard let mediaImage = Media(withImage: image, forKey: "profilePicture") else { return }
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    
    //create boundary
    let boundary = generateBoundary()
    
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    //call createDataBody method
    let dataBody = createDataBody(withParameters: parameters, media: [mediaImage], boundary: boundary)
    
    request.httpBody = dataBody as Data
    
    print(request.httpBody)
    
    URLSession.shared.dataTask(with: request) {
        data, response, error in
        if let data = data {
            do {
                
                let decoder = JSONDecoder()
                
                
                decoder.dateDecodingStrategy = .formatted(DateFormatter.customFormatter)
                
                let response = try decoder.decode(ReturnMessage.self, from: data)
                
                completionHandler(response)
                
            }catch(let error) {
                print(error.localizedDescription)
            }
        } else {
            print("No Data")
        }
    }.resume()
}

func generateBoundary() -> String {
    return "Boundary-\(NSUUID().uuidString)"
}

func createDataBody(withParameters params: Parameters?, media: [Media]?, boundary: String) -> Data {
    
    let lineBreak = "\r\n"
    var body = Data()
    
    if let parameters = params {
        for (key, value) in parameters {
            body.append("--\(boundary + lineBreak)")
            body.append("Content-Disposition: form-data; name=\"\(key)\"\(lineBreak + lineBreak)")
            body.append("\(value + lineBreak)")
        }
    }
    
    if let media = media {
        for photo in media {
            print(photo)
            body.append("--\(boundary + lineBreak)")
            body.append("Content-Disposition: form-data; name=\"\(photo.key)\"; filename=\"\(photo.filename)\"\(lineBreak)")
            body.append("Content-Type: \(photo.mimeType + lineBreak + lineBreak)")
            body.append(photo.data)
            body.append(lineBreak)
        }
    }
            
    body.append("--\(boundary)--\(lineBreak)")
    
    return body
}

I don't know if this is the right way to do it but any help is welcome.

thanks for you helping me guys

burnsi
  • 6,194
  • 13
  • 17
  • 27

0 Answers0