1

This code I use in Upload (I found it in a tutorial) is working successfully but the parameters is not being recognised instead of WHERE emp_name ='(insert employee)'it says emp_name='' because i'm trying to update the URL with the newly uploaded picture. Please help. i'm new to this.

 func UploadRequest()
{
    let url = URL(string: "http://www.example.com/empupload.php")

    let request = NSMutableURLRequest(url: url!)
    request.httpMethod = "POST"
    let boundary = generateBoundaryString()

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

    if (imageDetail.image == nil)
    {
        return
    }

    let image_data = UIImagePNGRepresentation(imageDetail.image!)


    if(image_data == nil)
    {
        return
    }


    let body = NSMutableData()
    let loadempname = NSMutableURLRequest()


    let fname = "test.png"
    let mimetype = "image/png"
    let postString = "empName=\(empname.text!))"


    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(postString.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 = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard ((data) != nil), let _:URLResponse = response, error == nil else {
            print("error")
            return
        }

        if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        {
            print(dataString)
        }

    })


    task.resume()


}
5
  • I suggest you use a third-party library like Alamofire for these complex requests. Commented Apr 11, 2017 at 5:48
  • \(empname.text!)) why there is two closing brackects while there is only one open bracket? Try removing one closing bracket Commented Apr 11, 2017 at 5:49
  • I'll try removing the bracket Commented Apr 11, 2017 at 5:51
  • Tried removing the bracket and the output is still the same. Commented Apr 11, 2017 at 6:55
  • Update! I used Alamofire and the parameters I used is now working and the photo URL in finally updating in mysql 😊 Commented Apr 12, 2017 at 15:42

1 Answer 1

1

You can post image through Alamofire multipartFormData in swift3.0. Here is sample code:

let  parameters = ["name":"YourName"]

Alamofire.upload(.POST, baseUrl, multipartFormData:
{
    multipartFormData in

    if  let imageData = UIImageJPEGRepresentation(self.imageView.image!, 0.6)
    {
        multipartFormData.appendBodyPart(data: imageData, name: "keyName", fileName: "photo.jpg", mimeType: "image/jpeg")
     }
     for (key, value) in parameters
     {
          if value is String || value is Int
          {
              multipartFormData.appendBodyPart(data: "\(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
           }

      }
}, encodingCompletion:
    {
        encodingResult in
        switch encodingResult
        {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                print(response)
                if String(response.result) == "SUCCESS"
                {
                    if(response.result.value!.objectForKey("status")) as! String != "fail"
                    {
                        // here you can write success case
                    }
                    else
                    {

                    }
                }
                else
                {
                    MyLoadingView.dismiss();
                    MyAlertView.showErrorAlert("Please try Again" )
                }
            }
            case .Failure(let encodingError):
                print(encodingError)
            }
    })
Sign up to request clarification or add additional context in comments.

2 Comments

How do I insert the url in the baseUrl? alamofire installed.
let baseUrl = "Your url"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.