1

In my app, users can select a photo from gallery to upload. After the user selects a photo, the following code gets called:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    self.dismissViewControllerAnimated(true, completion: { () -> Void in

    })

}

I need to upload the image in this method, but I don't know how to upload this photo to my server. I can post text with following code but I don't know how to use this for photo/s:

let request = NSMutableURLRequest(URL: NSURL(string: "url")!)
request.HTTPMethod = "POST"
let postString = "username=\(self.username)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
}
task.resume()

How can I upload a selected photo to my server with above code?

Quill
  • 2,729
  • 1
  • 33
  • 44
Tolgay Toklar
  • 4,151
  • 8
  • 43
  • 73

2 Answers2

0

What you're looking for is called Base64 encoding,
which could be called like this, and added to your POST request.

let base64String = imageData.base64EncodedStringWithOptions(.allZeros)
println(base64String)

A larger answer for this can be found here.

Good Luck!

Community
  • 1
  • 1
Quill
  • 2,729
  • 1
  • 33
  • 44
0

Where you assign HTTPBody, you can use something like this. I'm writing this in Objective-C.

NSMutableData *postData = [NSMutableData data]; 
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n", file]dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[NSData dataWithData:photo]];
[request setHTTPBody:postData];

Sorry for my coding, as I haven't done Swift, I hope you can translate it. By doing this you can upload your image, but this is not the right way of handling server request responses in iOS. you should use AFNetworking to deal with these. Look at this for more info.

Quill
  • 2,729
  • 1
  • 33
  • 44
Mahesh Agrawal
  • 3,348
  • 20
  • 34