I’ve been working on an App where you can take a picture and then it is send to a server via PHP (POST). Everything works fine, I get the picture. But now I was thinking that it would be better if you can show the name of the user that took the picture. The problem is, I don’t know how to send parameters from this Function to the PHP $_POST. I tried using request.httpBody but when I run the PHP file it says there is no value in the variable. My code looks like the following:
func subirFotoRequest(){
let url = URL(string: "http://192.168.0.155/BolsaTrabajo/imagen.php")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let postString = "username\(userName)&userlastname\(lastName)"
//Where userName and lastName are global variables declared before//
let request.httpBody = postString.data(using: String.Encoding.utf8)
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if (imageView.image == nil)
{
return
}
let image_data = UIImagePNGRepresentation(imageView.image!)
if(image_data == nil)
{
return
}
let body = NSMutableData()
indicadorActividad.startAnimating()
let fname = "test.png"
let mimetype = "image/png"
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-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
let session = URLSession.shared
let task = URLSession.shared.dataTask(with: request as URLRequest) { (
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
print("error")
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString)
//self.indicadorActividad.stopAnimating()
do {
DispatchQueue.main.async(execute: {
self.indicadorActividad.stopAnimating()
self.imageView.image = nil;
});
}
catch{
//Errores
}
}
task.resume()
}
func generateBoundaryString() -> String
{
return "Boundary-\(UUID().uuidString)"
}