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
Related
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>){
}
}
In my app i need to upload a audio file and xml file to server. I successfully post audio file. But i don’t know how to send two files in parallel. Anyone please help me.
NSString *soundFilePath = [[self GetDocumentDirectory]
stringByAppendingPathComponent:audioDet.audioName];
NSMutableData *file1Data = [[NSMutableData alloc] initWithContentsOfFile:soundFilePath];
//uploads/
NSString *urlString = #"http://192.168.1.99/projects/fileUpload/upload.php";
NSString *filename = audioDet.audioName;
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"];
[request setValue:#"Crystal" forHTTPHeaderField:#"ClientApp"];
[request setValue:#"1.0" forHTTPHeaderField:#"ClientVersion"];
[request setValue:#"617272656E64616C65445652" forHTTPHeaderField:#"ClientCredential"];
[request setValue:audioDet.audioName forHTTPHeaderField:#"Target-file-name"];
[request setValue:[NSString stringWithFormat:#"%#",audioDet.audioFileSize] forHTTPHeaderField:#"Target-file-length"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// NSString * value1 = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; name=\"%#\"\r\n", filename];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n", filename ] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:file1Data]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
Thanks,
AKS
Store the multiple files in an array and iterate the same using for loop to send multiple files in the server.
I need to implement a subclass of NSOperation which does a file upload to a HTTP server and with an option that the user can cancel the file upload during operation.
Here is the code at the moment:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:20];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"------WebKitFormBoundary4QuqLuM1cE5lMwCy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSString *FileParamConstant = #"uploadFile";
NSData *imageData = [[NSData alloc] initWithContentsOfFile:imagePath];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:11];
[parameters setValue:#"Value" forKey:#"Server_required_param"];
NSString *urlString = #"http://www.omeuendereco/uploadFile.php";
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", FileParamConstant, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setURL:[NSURL URLWithString:urlString]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:up
startImmediately:YES];
[connection start];
the problem is that i have to implement a NSOperationqueue in this code and i dont know how.
Then with the subclass of NSOperation i will be able to cancel the upload operation.
What the hell is your problem ? If you don't know how to make a subclass - learn Objective-C.
If I don't understand you (and there's some sophiscated problem, but I don't think so), you've got two solutions.
CREATE THAT SUBCLASS and then make an instance of NSOperationQueue, add an instance of that subclass to the queue.
Use AFNetworking or MKNetworkKit(MKNetworkKit uses NSOperation and NSOperationQueue)
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/
I'm playing around with trying to create a little menu item app to learn Cocoa/OS X programming.
Basically it's something that sits in your dock, you drag an image file to it, and it will upload the file to imgur and tell you the URL it was uploaded to.
It "works" in that imgur's API doesn't throw any errors back at me, but the images don't render properly either.
Applicable code:
ScreenshotController.m
- (void)uploadImage:(NSImage *)image
{
NSData *imageData = [image TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
NSString *base64 = [imageData encodeBase64WithNewlines: NO];
NSString *jsonRequest = #"key=92428d1a5839df89cb8e87e8a31cd935&image=";
jsonRequest = [jsonRequest stringByAppendingString:[base64 stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSLog(#"Request: %#", jsonRequest);
NSData *requestData = [NSData dataWithBytes: [jsonRequest UTF8String] length: [jsonRequest length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://api.imgur.com/2/upload"]];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: requestData];
NSData *returnData = [ NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Returned Json: %#", returnString);
}
StatusItemView.m
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *dragTypes = [NSArray arrayWithObjects:NSURLPboardType, NSFileContentsPboardType, NSFilenamesPboardType, nil];
[self registerForDraggedTypes:dragTypes];
}
return self;
}
//perform the drag and log the files that are dropped
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
NSPasteboard *pb = [sender draggingPasteboard];
if([[pb pasteboardItems] count] != 1){
return NO;
}
if([NSBitmapImageRep canInitWithPasteboard:pb]){
NSImage *image = [[NSImage alloc] initWithPasteboard:pb];
[[[ScreenshotController alloc] autorelease] uploadImage:image];
return YES;
}
return NO;
}
Here is an example image it uploaded to imgur, so you can see what I mean: http://imgur.com/6pLgG (the source file was a perfectly normal PNG).
Complete source code is here if you need to see anything else: https://github.com/zbuc/imgur
So I figured out a way to upload to the anon api, I hope this helps out.
- (void)uploadImageToImgur{
NSData *_imageData = UIImageJPEGRepresentation(image,90);
NSString *urlString = #"http://api.imgur.com/2/upload.json";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// file
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"image\"; filename=\".tiff\"\r\n" 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]];
// text parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//Set API key
[body appendData:[#"API_STRING_HERE" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSArray *decodedResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *imgurUrlString = [[[decodedResponse valueForKey:#"upload"] valueForKey:#"links"] valueForKey:#"imgur_page"];
[self uploadToImgurCompleteWithUrlString:imgurUrlString];
}];
}