1

this is my current code here:

let request = NSMutableURLRequest(URL: NSURL(string: "http://www.example.com/upload.php"))
request.HTTPMethod = "POST"
let postString = "name=\(name)&id=\(id)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
        print("error=\(error)")
        return
    }

    let response = String(data: data!, encoding: NSUTF8StringEncoding)
}
task.resume()

my image is myImage.image.

how can i add the image upload into there the code above?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
johnjay22113
  • 133
  • 3
  • 10

1 Answers1

0

Try this i hope it would be helpfull!!

func myImageUploadRequest()
    {

        let myUrl = NSURL(string: "http://www.YourRestapi/postImage.php");

        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";

        let param = [
            "firstName"  : "abc",
            "lastName"    : "xyz",
            "userId"    : "1"
        ]

        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


        let imageData = UIImageJPEGRepresentation(myImageView.image, 1)

        if(imageData==nil)  { return; }

        request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)



        myActivityIndicator.startAnimating();

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                println("error=\(error)")
                return
            }

            // You can print out response object
            println("******* response = \(response)")

            // Print out reponse body
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("****** response data = \(responseString!)")

            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary



            dispatch_async(dispatch_get_main_queue(),{
                self.myActivityIndicator.stopAnimating()
                self.myImageView.image = nil;
            });

       /*
            if let parseJSON = json {
                var firstNameValue = parseJSON["firstName"] as? String
                println("firstNameValue: \(firstNameValue)")
            }
        */

        }

        task.resume()

    }


    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
        var body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

                let filename = "user-profile.jpg"

                let mimetype = "image/jpg"

                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
                body.appendString("Content-Type: \(mimetype)\r\n\r\n")
                body.appendData(imageDataKey)
                body.appendString("\r\n")



        body.appendString("--\(boundary)--\r\n")

        return body
    }




    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().UUIDString)"
    }



}extension NSMutableData {

        func appendString(string: String) {
            let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
            appendData(data!)
        }
    }
Sanjeet Verma
  • 551
  • 4
  • 15