Question

I am a newbie of XCode and Objective-C, and I followed the example in http://www.techotopia.com/index.php/An_Example_iOS_4_iPhone_Camera_Application_(Xcode_4), and so that I have an apps that can call the camera in device (in my case, I am using iPod Touch) and capture the picture, then it can shows the picture in the image view, or select the picture in the camera roll to show in the image view. This is tested and worked perfectly in my iPod Touch.

Now, I want to add an upload button that can upload the image that captured to my server (e.g.: http://xxx.xxx.xxx.xxx/photo/) so that I can view the image in my computer, anyone can suggest a method to let me do so? Or if it can not be done, am I need to set-up a php based server to handle this upload problem.

Was it helpful?

Solution

You wanna upload an image to php server, in objective-c which you can do this :

//To convert your image file to raw.
NSData *imageData   = UIImagePNGRepresentation(self.imageView.image);
NSString *urlString = @"http://sample.com/upload.php";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
//Boundary and Header.
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
//Your uploading file.
NSMutableData *bodyData = [NSMutableData data];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
/*
 * Declares the PHP received $_FILES variables.
 * - $_FILES['_varName']['name'] = _sample.png
 */
[bodyData appendData:[@"Content-Disposition: form-data; name=\"_varName\"; filename=\"_sample.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[bodyData appendData:[NSData dataWithData:imageData]];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:bodyData];
//Received response of server.
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
//Dumps it.
NSLog(@"%@", returnString);

May it can help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top