Uploading Image via POST in Objective C - objective-c

I'm currently working on uploading an image to a server via HTTP Post and can't seem to figure out a way to build the url that calls the service. The user selects an image from the library or camera and then calls a json service that performs the insert statement.
The service is expecting the following uritemplate:
#"%#/DataTransfer/SetUserProfileImage?EMP_ID=%#&image=%#&imageName=%#"
It is expecting that the image data is converted somehow to string and sent over url.
This is my current code:
- (BOOL)setUserProfileImage:(UIImage *)imgUser Name:(NSString *)strName{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSData *dataImage = UIImagePNGRepresentation(imgUser);
NSString* theNSString = [[NSString alloc] initWithData:dataImage encoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/DataTransfer /SetUserProfileImage?EMP_ID=%#&"
"image=%#&imageName=%#",
appDelegate.ServerAddress,
appDelegate.UserId,
theNSString,
strName]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLResponse* response = nil;
NSError* resultError = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&resultError];
NSString *strResult = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
BOOL imgResponse = [strResult boolValue];
[strResult release];
return imgResponse;
}
I get an error saying that the NSURL is "". Can't seem to build a correct URL. I know that the service itself converts this string to an image again.
UPDATE:
- (BOOL)setUserProfileImage:(UIImage *)imgUser Name:(NSString *)strName{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *url = [NSString stringWithFormat:#"%#/DataTransfer/SetUserProfileImage",appDelegate.ServerAddress];
NSData *data = UIImagePNGRepresentation(imgUser);
NSString * boundary = #"tweetPhotoBoundaryParm";
NSMutableData *postData = [NSMutableData dataWithCapacity:[data length] + 1024];
name=\"EMP_ID\"\r\n\r\n%#", #"100-01"];
NSString * boundaryString = [NSString stringWithFormat:#"\r\n--%#\r\n", boundary];
NSString * boundaryStringFinal = [NSString stringWithFormat:#"\r\n--%#--\r\n", boundary];
[postData appendData:[boundaryString dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\";\r\nfilename=\"media.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:data];
[postData appendData:[boundaryStringFinal dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest * theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
//[theRequest addValue:#"www.tweetphoto.com" forHTTPHeaderField:#"Host"];
NSString * dataLength = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:(NSData*)postData];
NSURLConnection * theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
webData =[[NSMutableData data] retain];
}
else
{
NSLog(#"%#",#"Could not connect to the network");
}
return false;
}

Objective-C
-(void)saveImageToServer
{
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"yourImage"], 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"Your URL HERE";
// set your Image Name
NSString *filename = #"YourImageFileName";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}
Swift
// COnvert Image to NSData
var dataImage: NSData = UIImageJPEGRepresentation(UIImage(named: "yourImage"), 1.0)
// set your URL Where to Upload Image
var urlString: String = "Your URL HERE"
// set your Image Name
var filename: String = "YourImageFileName"
// Create 'POST' MutableRequest with Data and Other Image Attachment.
var request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: urlString)!
request.HTTPMethod = "POST"
var boundary: String = "---------------------------14737809831466499882746641449"
var contentType: String = "multipart/form-data; boundary=\(boundary)"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
var postbody: NSMutableData = NSMutableData.data()
postbody.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData("Content-Disposition: form-data; name=\"userfile\"; filename=\"\(filename).jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData(String.stringWithString("Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData(NSData.dataWithData(dataImage))
postbody.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding))
request.HTTPBody = postbody
// Get Response of Your Request
var returnData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
var responseString: String = String(data: returnData, encoding: NSUTF8StringEncoding)
NSLog("Response %#", responseString)

This approach has several problems.
1) Converting the raw bytes of a image into a string will never work.
NSData *dataImage = UIImagePNGRepresentation(imgUser);
NSString* theNSString = [[NSString alloc] initWithData:dataImage encoding:NSASCIIStringEncoding];
Will fail. You will never be able to reconstruct dataImage from theNSString. You need to base 64 encode dataImage. Use something like this to do the base 64 encoding.
2) Don't put image data into a URL. You need to put the image data in a post body.
3) Don't use "application/x-www-form-urlencoded", use "multipart/form-data".
Updated after Comments
Sorry, but it looks like you have a lot of work to do in understanding your system.
In the example above, you added all the data to the URL query string, but did not add anything to the body of the message. In that example you set the content type to be "application/x-www-form-urlencoded".
Now you seem to think the POST needs to be in JSON. You need to find out how that should be done. How does that JSON message need to be attached? Before you said the data needed to be in the URL, is this still the case? If you need to attach the JSON message to the POST body, what does the content type of the POST need to be? What is the structure of the JSON message (all the key/value fields needed)?
Before anyone can help you, you need to find out exactly what's needed. There should be someone who can give you an accurate description of the HTTP message.

Related

How can I upload an image file from saved NSUserDefault to php server?

I would like to change profile image in my apps and upload the image to PHP server after edited. So far I saved my changed profile image to local.
My question is how can I upload the changed image to PHP server (upload image file)? Can I use AFNetworking 3.X and I need to write backend API for this case? Is there any method to upload the image file to server directly?
Here is what I done so far by using UIImagePickerController and it is working fine until this stage:-
-(void)changeProfileImage:(UITapGestureRecognizer *)recognizer{
if (!_photoManager) {
_photoManager =[[SelectPhotoManager alloc]init];
}
[_photoManager startSelectPhotoWithImageName:#"Select Profile Image"];
__weak typeof(self)mySelf=self;
//Select Photo
_photoManager.successHandle=^(SelectPhotoManager *manager,UIImage *image){
mySelf.imgProfileImage.image = image;
NSData *data = UIImagePNGRepresentation(image);
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"imgProfile"];
};
}
Please help. Thank you.
// HTTP method to upload file to web server
-(void)initWithURL:(NSString *)url image:(NSData *)imageData andFileName:(NSString *)filename delegate:(id)del {
// your PHP server url
// your image data
NSString *urlString = url;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
// if access token defined for authrization
NSString *token = [NSString stringWithFormat:#"Bearer %#",[[[CommonUserDefault getUserInfo] objectForKey:#"token"] objectForKey:#"accessToken"]];
[request addValue:token forHTTPHeaderField: #"Authorization"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"files\"; filename=\"%#.jpg\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
id json = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];
NSLog(#"json upload picture = %#",json);
int statusCode = [[json objectForKey:#"statusCode"] intValue];
if(statusCode == <errorCode>){
}
}

How to send HTTP POST request to PHP service with Objective-C

Im trying to post to php and get the response. The php file has an echo "hello" which should just print hello. I'm trying to test to see if posting is working but in my error log the NSlog doesn't display anything:
#interface ViewController ()
#end
#implementation ViewController
#synthesize email, password,receivedData;
-(IBAction)Login:(id)sender{
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://grouporder.site90.net/test.php"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:#"%#", email];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//initialize convert the received data to string with UTF8 encoding
NSString *htmlSTR = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(#"%#" , htmlSTR);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"%#" , error);
}
Since you did not mention about what kind of body type you want to use this example shows you how to post multipart/form-data request.
-(NSString *)generateRandomBoundryString {
CFUUIDRef UUID = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef UUIDString = CFUUIDCreateString(kCFAllocatorDefault,UUID);
NSString *aNSString = (__bridge NSString *)UUIDString;
CFRelease(UUID);
CFRelease(UUIDString);
return aNSString;
}
-(IBAction)Login:(id)sender {
NSString *bndry = [self generateRandomBoundryString];
NSString *contentType = [[NSString alloc] initWithString:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", bndry]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://grouporder.site90.net/test.php"]];
[request setHTTPMethod:#"POST"];
[request setValue: contentType forHTTPHeaderField:#"Content-Type"];
//form-data block
NSMutableData *requestBody = [NSMutableData data];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"%#=%#", #"name", #"John"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"%#=%#", #"password", #"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:requestBody];
//form-data block
// NSURLConnection Asynchronous Block
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rspreportStatus, NSData *datareportStatus, NSError *e)
{
if (e == nil)
{
// If all ok you can processes response data here.
}
else {
NSLog(#"%#", e.localizedDescription);
}
}];
}
If body is application/x-www-form-urlencoded you should change Content-Type value like this.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
and replace //form-data block block with this.
[requestBody appendData:[[NSString stringWithFormat:#"name=%#&password=%#", #"John", #"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
#"John" and #"myPassword" has to be URL encoded.

Upload A File Into A Server - Objective C/Xcode/Mediawiki

I want to upload a UIImage into a server. For this I am using the following lines of code ::
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
imageView.image = image;
NSData *pngData = UIImagePNGRepresentation(imageView.image);
NSString *imageFile = #"image.png";
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [docDir stringByAppendingPathComponent:imageFile];
NSString *dataIS=[NSString base64StringFromData:pngData length:[pngData length]];
[pngData writeToFile:filePath atomically:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:pngData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
But, I am getting the following error in gdb ::
Your request could not be processed. Request could not be handled.
I am also confused over the proper use of urlString i.e. I am doubtful over my correct use of it.
If I however use the following urlString, I am able to upload my image file into the server ::
NSString *urlString = [NSString stringWithFormat:#"http://xxxx.com/mediawiki/api.php?action=upload&filename=image.png&url=%#&token=%#", url, token] ;
With reference to the API for mediawiki (http://www.mediawiki.org/wiki/API:Upload), can someone help me to sort it out ?? Thanks and Regards.
I have same problem to upload multiple images and data but i am use AFNetworking class and Upload multiple images into server.
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"your URL"]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
path = [[NSString alloc] initWithString:[URL absoluteString]];
vdict = #{
// Your Parameter Pass
};
[self checkmultiple:vdict];
-(void)checkmultiple:(NSDictionary*)vdict
{
AFHTTPRequestOperation *op = [manager POST:path parameters:vdict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
for(i = 0;i<[appDelegate.gblarrydata count];i++)
{
NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"New Folder"];
// NSLog(#"%#",paths);
NSString *documentsDirectory = paths;
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[[appDelegate.gblarrydata objectAtIndex:i]valueForKey:#"nameimage"]];
NSData *data1 =[[NSData alloc]initWithContentsOfFile:getImagePath];
NSString *data2 =[[appDelegate.gblarrydata objectAtIndex:i] valueForKey:#"Note"];
[formData appendPartWithFileData:data1 name:[NSString stringWithFormat:#"pimage%d",i+1] fileName:[NSString stringWithFormat:#"pimage%d.jpg",i+1] mimeType:#"image/jpeg"];
if(![data2 isEqualToString:#""])
{
[formData appendPartWithFormData:[data2 dataUsingEncoding:NSUTF8StringEncoding]
name:[NSString stringWithFormat:#"pnotes%d",i+1]];
}
}
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Upload success");
NSString *returnString = [NSString stringWithFormat:#"%#",[responseObject JSONRepresentation]];
NSLog(#"Reg Date:%#",returnString);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error:%#",error);
}];
[op start];
}
I had the same problem. I used ASIHTTPRequest, for uploading files, it works fine.
Uploading:
Imagefile:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
With Other data simultaneously:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// Upload a file on disk
[request setFile:#"/Users/ben/Desktop/ben.jpg" withFileName:#"myphoto.jpg" andContentType:#"image/jpeg"
forKey:#"photo"];
// Upload an NSData instance
[request setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
for Downloading to desired Path:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:#"/Users/ben/Desktop/my_file.txt"];
If you want to send image to server,send by data in encoded form,server can handle encoded form of image and they will get image data in encoded from.
// UIImage * img = [UIImage imageNamed:#"min.png"];
// NSData *imageData = UIImageJPEGRepresentation(img,0.2);
NSString *strUrl =[NSString stringWithFormat:#"%#/upload_file.php", [globalApp sharedUser].vg_dominio ];
//strUrl = #"http://192.168.1.100/mismedicinas/upload_file.php";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
request.HTTPMethod = #"POST";
request.timeoutInterval = 60;
request.HTTPShouldHandleCookies = false;
//[request setHTTPMethod:#"POST"];
NSString *boundary = #"----------SwIfTeRhTtPrEqUeStBoUnDaRy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
//[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableData *tempData = [NSMutableData data];
[tempData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[tempData appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphoneimage.xml\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[tempData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[tempData appendData:[NSData dataWithData:imageData]]; ///IMAGEN
[tempData appendData:[NSData dataWithData:cData]];
[tempData appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData: tempData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue: [NSString stringWithFormat:#"%d", body.length ] forHTTPHeaderField:#"Content-Length"];
request.HTTPBody =body;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"finalizacion %#", returnString);

iOS YouTube Video Upload Error

I am trying to upload a video using Objective-C and YouTube API but it is not working and return error at last step. The error reads "User authentication required".
I am following this API document specifically the one which is without metadata. I got the authentication token with ClientLogin API
I checked authentication token with NSLog and it's there. I see the upload API also returns Upload URL but when I send HTTP PUT request to retrieved Upload URL, it returns an error mentioned above.
Here's Upload Code
- (bool) upload:(NSString *)file {
NSData *fileData = [NSData dataWithContentsOfFile:file];
NSURL *url = [NSURL URLWithString:self.UploadURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"PUT"];
[request setValue:#"Content-Type" forHTTPHeaderField:#"application/octet-stream"];
[request setValue:#"Content-Length" forHTTPHeaderField:[NSString stringWithFormat:#"%ud", [fileData length]]];
[request setHTTPBody:fileData];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
if (response == nil) {
return NO;
} else {
return YES;
}
}
I also tried the Direct Upload method but this always gives me Invalid Request error. Below is the code.
- (bool) directUpload:(NSString *)file {
NSString *title = [file lastPathComponent];
NSString *desc = #"This is test video.";
NSString *category = #"People";
NSString *keywords = #"video";
NSString *boundary = #"--qwerty";
NSString *xml = [NSString stringWithFormat:
#"<?xml version=\"1.0\"?>"
#"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
#"<media:group>"
#"<media:title type=\"plain\">%#</media:title>"
#"<media:description type=\"plain\">%#</media:description>"
#"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%#</media:category>"
#"<media:keywords>%#</media:keywords>"
#"</media:group>"
#"</entry>", title, desc, category, keywords];
NSData *fileData = [NSData dataWithContentsOfFile:file];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"%#\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Type: application/atom+xml; charset=UTF-8\n\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Type: video/mp4\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Transfer-Encoding: binary\n\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:fileData];
[postBody appendData:[[NSString stringWithFormat:#"%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=\"%#\"", self.AuthToken] forHTTPHeaderField:#"Authorization"];
[request setValue:#"2" forHTTPHeaderField:#"GData-Version"];
[request setValue:[NSString stringWithFormat:#"key=%#", self.DeveloperKey] forHTTPHeaderField:#"X-GData-Key"];
[request setValue:[file lastPathComponent] forHTTPHeaderField:#"Slug"];
[request setValue:[NSString stringWithFormat:#"multipart/related; boundary=\"%#\"", boundary] forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%ud", [postBody length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"close" forHTTPHeaderField:#"Connection"];
[request setHTTPBody:postBody];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
if (response == nil) {
return NO;
} else {
return YES;
}
}
i think you should check this :-
https://developers.google.com/youtube/2.0/developers_guide_protocol_video_feeds
and you also check this :-
http://urinieto.com/2010/10/upload-videos-to-youtube-with-iphone-custom-app/

-[NSConcreteMutableData release]: message sent to deallocated instance

I am facing a problem of -[NSConcreteMutableData release]: message sent to deallocated instance, i have attached my sample code as well.
- (IBAction)uploadImage {
NSString *urlString = #"http://192.168.1.108/iphoneimages/uploadfile.php?userid=1&charid=23&msgid=3";
//if(FALSE)
for (int i=0; i<[imgArray count]; i++) {
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [[NSMutableData data] autorelease];
NSString *str = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile%d.jpg\"\r\n",i];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *imageData = UIImageJPEGRepresentation([imgArray objectAtIndex:i], 90);
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",returnString);
[imageData release];
[request release];
//[body release];
}
}
It successfully upload the images to the folder and there is no any error in the execution but when it complete it process and try to go back it give error -[NSConcreteMutableData release]: message sent to deallocated instance
Please help me out.
Thanks
UIImageJPEGRepresentation returns an auto released object and you release it. When this is auto released it will blow up.
NSMutableData *body = [[NSMutableData data] autorelease];
remove that autorelease message