1
votes

I am working on an iOS application , in which i have to upload image to the server , I am working with swift 2.0. Below is the code :

var tempImage:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage myImage.image = tempImage

    print(tempImage)

    print([info])

    myImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    self.dismissViewControllerAnimated(true, completion: nil)
    var imageData = UIImagePNGRepresentation(tempImage)

    // converting in base64
    let base64 = imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) as! AnyObject

    let url = NSURL(string: "www.google.com/myimage1/PNG")!

    let urlRequest = NSMutableURLRequest(URL: url)
    urlRequest.HTTPMethod = "POST"

    // Set the HTTP Body with the POST data
    let postDict = ["encodedImage": base64]

    urlRequest.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(postDict , options: [])

    urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")


    urlRequest.timeoutInterval = 600
    urlRequest.HTTPShouldHandleCookies = false
 //   urlRequest.setValue("application/json)", forHTTPHeaderField: "Content-Type")

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

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

        print("response = \(response)")

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    task.resume()

But i am not succeded yet. I am still getting the below error response.

error=Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fad5af61e20 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=60, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=www.google.com/myimage1/PNG, NSErrorFailingURLKey=http://www.google.com/myimage1/PNG, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=60, NSLocalizedDescription=The request timed out.})

Please help me out , if you already have uploaded image on server from your application in swift 2.0.

2

2 Answers

1
votes

You need to change your file

info.plist

, and add this with the app TextEdit, or use xcode.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    </dict>
</dict>

from Xcode http://i.stack.imgur.com/tGsEK.png

,And don't forget clean the project. (cmd + shift + k)

0
votes
func uploadImageOne()
{
    var imageData = UIImagePNGRepresentation(imageView.image)

    if imageData != nil{
        var request = NSMutableURLRequest(URL: NSURL(string:"= Enter your image URL")!)
        var session = NSURLSession.sharedSession()

        request.HTTPMethod = "POST"

        var boundary = NSString(format: "---------------------------14737809831466499882746641449")
        var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
      //  println("Content Type \(contentType)")
        request.addValue(contentType, forHTTPHeaderField: "Content-Type")

        var body = NSMutableData.alloc()

        // Title
         body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(NSString(format:"Content-Disposition: form-data; name=\"title\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

        // Image
        body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(imageData)
        body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)



        request.HTTPBody = body


        var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)

        var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding)

        println("returnString \(returnString)")

    }