0

I'm developing an iOS app with Xcode and Swift.

I usually take this code to POST data to PHP:

let requestImage = NSMutableURLRequest(URL: NSURL(string: "http://example.com/postData.php")!)
requestData.HTTPMethod = "POST"
let postStringImage = "name=\(name.text!)&age=\(age.text!)"
requestData.HTTPBody = postStringImage.dataUsingEncoding(NSUTF8StringEncoding)

Now I want to post an image that's in a UIImageView to PHP: Can I simple do something like this? Code:

let requestImage = NSMutableURLRequest(URL: NSURL(string: "http://example.com/postImage.php")!)
requestData.HTTPMethod = "POST"
let postStringImage = "image=\(MyImage)"
requestData.HTTPBody = postStringImage.dataUsingEncoding(NSUTF8StringEncoding)

What do I have to do to make it working?

BTW:

I took this code to test my PHP script via browser:

<form action="postImage.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload">
    <input type="submit" value="Upload Image">
</form>
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

You have a PHP script that accepts multipart/form-data. Because this you need your POST request to be a multipart/form-data. Try this example:

https://stackoverflow.com/a/24252378/2441775

If you have any question, feel free to request again. I'll try to answer.

Community
  • 1
  • 1
Mário Klein
  • 93
  • 1
  • 5
  • David, there are lot's of samples in stack overflow to your problem. In the same answer that comment, I found another, this time in swift. Try this: http://stackoverflow.com/a/26163136/2441775 I don't develop in swift, because that I can't help too much, but the main idea is in booth samples. – Mário Klein Sep 13 '16 at 20:49
  • I'm not able to get it working. Maybe because I'm doing something wrong when trying to convert the Objective-c code to Swift code (because I use Swift in my project). Do you know a better solution? Or is there a library for it? –  Sep 13 '16 at 20:51
  • David, post your code to me. I can try analyze to find the problem. – Mário Klein Sep 14 '16 at 18:58
  • Hey, @Mário Klein, thanks for trying to help me. Do you mean the Objective-c code I tried to convert in Swift code? –  Sep 15 '16 at 15:00
  • Hi David, no problem. I mean the code in swift that doesn't works for you. I can try to identify the problem. – Mário Klein Sep 16 '16 at 13:44