iphone graph api not working to post image in facebook - iphone

using this method to post the image
- (void)postInAppFacebook {
btnForLogout.hidden=NO;
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:3];
NSData *imageData = UIImageJPEGRepresentation(imgPicture.image, 4.0);
UIImage *picture = [[UIImage alloc]initWithData:imageData];
FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:picture];
[variables setObject:graph_file forKey:#"file"];
[variables setObject:[NSString stringWithFormat:#"%#", txtComment.text] forKey:#"message"];
**[fbGraph doGraphPost:#"me/photos" withPostVars:variables];**
NSLog(#"Now log into Facebook and look at your profile & photo albums...");
UIAlertView *alertForImageHasPost=[[UIAlertView alloc]initWithTitle:#"MAP IMAGE POST" message:#"SELECTED IMAGE POSTED" delegate:self cancelButtonTitle:#"CANCEL" otherButtonTitles:#"OK",nil];
[alertForImageHasPost show];
[alertForImageHasPost release];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
problem in this method
second time its crash but working well in simulator
- (FbGraphResponse *)doGraphPost:(NSString *)action withPostVars:(NSDictionary *)post_vars {
NSLog(#"action is %#",action);
FbGraphResponse *return_value = [[FbGraphResponse alloc] init];
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#", action];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = #"----1010101010";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [post_vars keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
//loop through all our parameters
while ((key = (NSString *)[enumerator nextObject])) {
//if it's a picture (file)...we have to append the binary data
if ([key isEqualToString:#"file"]) {
/*
* the FbGraphFile object is smart enough to append it's data to
* the request automagically, regardless of the type of file being
* attached
*/
FbGraphFile *upload_file = (FbGraphFile *)[post_vars objectForKey:key];
[upload_file appendDataToBody:body];
//key/value nsstring/nsstring
} else {
value = (NSString *)[post_vars objectForKey:key];
content_disposition = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}//end else
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}//end while
//add our access token
[body appendData:[#"Content-Disposition: form-data; name=\"access_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[accessToken dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//button up the request body
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", body.length] forHTTPHeaderField: #"Content-Length"];
//quite a few lines of code to simply do the business of the HTTP connection....
NSURLResponse *response;
NSData *data_reply;
NSError *err;
**//crash after this line**
***
> data_reply = [NSURLConnection sendSynchronousRequest:request
> returningResponse:&response error:&err];
***
return_value.htmlResponse = (NSString *)[[NSString alloc] initWithData:data_reply encoding:NSUTF8StringEncoding];
if (err != nil) {
return_value.error = err;
}
/*
* return the json array. we could parse it, but that would incur overhead
* some users might not want (not to mention dependencies), besides someone
* may want raw strings back, keep it simple.
*
* See: http://code.google.com/p/json-framework for an easy json parser
*/
return return_value;
}

Have a look at below functions. I hope you will get success with it.
Please have a look at all the methods as below:
- (IBAction)uploadPhoto:(id)sender {
[self postOnFacebook];
}
//Post Message and Photos on Facebook Function
-(void)postOnFacebook
{
NSString *strPostMessage = [self createMessageForPostOnFacebook:74.112 withLongitude:21.85];
//UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objClsProductSearch.strProductImageURL]]];
//UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg"]]];
UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://d1xzuxjlafny7l.cloudfront.net/wp-content/uploads/2011/08/HUDTutorial.jpg"]]];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
strPostMessage,#"message",img, #"source",
nil];
[_facebook requestWithGraphPath:#"/me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
[img release];
}
//Create Message for posting on Facebook
-(NSString *)createMessageForPostOnFacebook:(double)pfltLatitude withLongitude:(double)pfltLongitude
{
//NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pfltLatitude, pfltLongitude];
//NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",#"", #""];
//NSError* error;
//NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
//NSArray *listItems = [locationString componentsSeparatedByString:#","];
NSString *strMessage = nil;
/*if([[listItems objectAtIndex:0] isEqualToString:#"200"])
{
strMessage = [NSString stringWithFormat:#"I found a %# using BH for iPhone \n Location : %# \n Latitude : %f & Longitude : %f \n Product Rating : %d",objClsProductSearch.strCategoryname,[locationString substringFromIndex:6],appDelegate.dblLatitude,appDelegate.dblLongitude,btnTmp.tag];
}*/
strMessage = [NSString stringWithFormat:#"I found a %# using BH for iPhone \n Location : %# \n Latitude : %f & Longitude : %f \n Product Rating : %d", #"Cat Name", #"Location", 74.112, 21.85, 1];
return strMessage;
}
I hope you will have success using the above code.
Let me know in case of any difficulty.
In you app delegate, have a look at below methods whether it is implemented or not.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//return [[controller facebook] handleOpenURL:url];
//return [[objPage2ViewController facebook] handleOpenURL:url];
return [[[self.navigationController topViewController] facebook] handleOpenURL:url];
}
Cheers

Related

how to pass parameter to NSMutableURLRequest object?

I am sending request to using NSMutableURLRequest but not getting the response can anyone suggest me the proper way to do that.
The code below is the solution.
-(void)setName:(NSString *)name withValue:(NSString *)value onBody:(NSMutableData *)body{
NSString *boundary = #"---------------------------14737809831466499882746641449";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
-(BOOL)SetRequest: (NSString *)offerID UserID: (NSString*) userID imageData:(NSData *) imageData RespData: (NSDictionary **)respData {
NSMutableData *body=[NSMutableData data];
//NSArray *paramNames = [NSArray arrayWithObjects:#"offerid", #"userid", nil];
//NSArray *paramDatas = [NSArray arrayWithObjects:offerID, userID, nil];
//NSDictionary *dict = [[NSDictionary alloc] initWithObjects:paramDatas forKeys:paramNames];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"API URL"]]];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[self setName:#"userid" withValue:userID onBody:body];
[self setName:#"offerid" withValue:offerID onBody:body];
// Title text parameter
NSString *fileName = [NSString stringWithFormat:#"%#_%#.jpg",userID,offerID];
// NSData *uploadData = imageData;
//uploadData = UIImageJPEGRepresentation([UIImage imageWithData:imageData], 1.0f);
[self setName:#"parameterName" withFileName:fileName withValue:imageData onBody:body];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];
NSDictionary *dic = (NSDictionary *)[parser objectWithString:returnString error:nil];
if (dic == nil)
return NO; // invalid JSON format
[dic retain];
*respData = dic;
return YES;
}

Uploading video file to server but gets posted in bytes

Trying to post the video file to server, getting posted in bytes. Posting my code below i am using for posting.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ( [mediaType isEqualToString:#"public.movie" ])
{
if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0)
== kCFCompareEqualTo)
{
NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
NSData *webData = [NSData dataWithContentsOfURL:videoUrl];
[self post:webData];
if([profile isEqualToString:#"friend"])
{
[self callServerFriend];
}
if([profile isEqualToString:#"public"])
{
[self callServerPublic];
}
}
}
- (void)post:(NSData *)fileData
{
NSLog(#"POSTING");
index1 = [[NSUserDefaults standardUserDefaults] integerForKey:#"videoName"];
valIndex1 = index1;
NSString *str = [NSString stringWithFormat:#"video_%d.mp4",valIndex];
// Generate the postdata:
NSData *postData = [self generatePostDataForData: fileData];
profileImg = profilePic;
NSArray *arrImg = [profileImg componentsSeparatedByString:#"/"];
NSString *strImg1 = [arrImg objectAtIndex:[arrImg count]-2];
NSString *strImg2 = #"/";
NSString *strImg3 = [arrImg lastObject];
//NSLog(#"img2-----------------%#",strImg2);
NSString *pImg = [NSString stringWithFormat:#"%#%#%#",strImg1, strImg2, strImg3];
NSLog(#"img-----------------%#",pImg);
// Setup the request:
NSString *urlString = [[NSString stringWithFormat:#"http://www.myvnt.co/overheadPost.php?userId=%#&type=Video&text=%#&image=%#&location=%#&Upload=Upload", uid, statusPost, pImg, locc]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *wigiRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[wigiRequest setHTTPMethod:#"POST"];
// just some random text that will never occur in the body
NSString *stringBoundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
// header value
NSString *headerBoundary = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",
stringBoundary];
// set header
[wigiRequest addValue:headerBoundary forHTTPHeaderField:#"Content-Type"];
//add body
NSMutableData *postBody = [NSMutableData data];
NSLog(#"body made");
//IMAGE Posting
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
//"Content-Disposition: form-data; name=\"fileUpload\";filename=\"" + imagePath + "\"" + lineEn
//[postBody appendData:[#"Content-Disposition: form-data; name=\"fileUpload\"; filename=\"img.mp4\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"fileUpload\"; filename=\"%#\"\r\n", str]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: image/png\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"uploadFile\"; filename=\"img.mp4\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
//[postData setData:postHeaderData];
// add it to body
[postBody appendData:postData];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// final boundary
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add body to post
[wigiRequest setHTTPBody:postBody];
NSLog(#"body set");
// pointers to some necessary objects
NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
NSError* error = [[NSError alloc] init] ;
// synchronous filling of data from HTTP POST response
NSData *respData = [NSURLConnection sendSynchronousRequest:wigiRequest returningResponse:&response error:&error];
NSLog(#"just sent request");
NSString *responseHTML = [[NSString alloc] initWithBytes:[respData bytes]
length:[respData length]
encoding:NSUTF8StringEncoding];
NSLog(#"response dictionary : %#",responseHTML);
index1++;
[[NSUserDefaults standardUserDefaults] setInteger:index forKey:#"videoName"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSData *)generatePostDataForData:(NSData *)uploadData
{
// Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"uploadFile\"; filename=\"img.mp4\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
[postData appendData: uploadData];
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
And another thing is it posting the video with the same name every time so every new post replace the previous one. But the main issue is why it posting in bytes i am not getting that.
Please guide for above. Thanks in advance.
Try this, I've stored it with current Date-Time ::
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[self dismissViewControllerAnimated:NO completion:nil];
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
// Code To give Name to video and store to DocumentDirectory //
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy||HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
theDate = [dateFormat stringFromDate:now];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mov",documentsDirectory,theDate]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
}
}
Video Uploading ::
videoData is getting from videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
- (void)uploadVideo
{
NSData *imageData = videoData;
NSString *urlString=[NSString stringWithFormat:#"%s", UploadVideoService];
NSLog(#"url=== %#", urlString);
request = [[[NSMutableURLRequest alloc] init] autorelease];
[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"];
/* body of the post */
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Video Name with Date-Time
NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"yyyy-MM-dd-hh:mm:ssa"];
NSString *currDate = [dateFormat stringFromDate:[NSDate date]];
NSString *str = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"video-%#.mov\"\r\n", currDate];
NSLog(#"String name:: %#",str);
[dateFormat release];
[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"result from webservice:::--> %#", returnString);
[returnString release];
}
Hope, it'll help you.
Thanks.

Update UIProgressView while posting video to php

I am trying to figure out how to update my UIProgressView while i upload a video to my server. The video is a user picked video, here is my code to upload to my server:
NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:[self saveUserLogin]];
int test;
NSString *string = [array objectAtIndex:3];
test = [string intValue];
test++;
NSData *videoData = fileData;
NSString *urlString = [[NSString alloc]initWithFormat:#"http://www.site.com/members/uploadMovie.php?&username=%#", [array objectAtIndex:0]];
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]];
NSString *postName = [[NSString alloc]initWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"vid%i.mov\"\r\n", test];
[body appendData:[[NSString stringWithString:postName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
NSArray *values = [[NSArray alloc] initWithObjects: [array objectAtIndex:0],[array objectAtIndex:1], [array objectAtIndex:2], [NSString stringWithFormat:#"%i", test], nil];
[values writeToFile:[self saveUserLogin] atomically:YES];
[self.delegate didFinishController:self];
My UIProgressView is named ProgressForUpload, I am guessing that i'll have to use a new thread. This app i am making also uploads images, I am able to update the progressview for the images by doing this:
int copy = ForProgress;
ForProgress = 100 / ForProgress;
NSString *togetridof = [[NSString alloc]initWithFormat:#"%f", ForProgress];
NSString *stringWithoutdot = [togetridof stringByReplacingOccurrencesOfString:#"." withString:#""];
if(copy > 1 && copy < 11){
progressString = [[NSString alloc]initWithFormat:#"0.%#", stringWithoutdot];
}
if (copy > 10) {
progressString = [[NSString alloc]initWithFormat:#"0.0%#", stringWithoutdot];
}
if(ForProgress == 100){
progressString = [[NSString alloc]initWithFormat:#"%#", stringWithoutdot];
}
tellprogress = [progressString floatValue];
Then while i upload images i create a new thread that will add tell progress onto the current progress, until its done.
I dont know if anything like this would apply to uploading a video though.
Thanks, Jacob
I'd implement this using asynchronous networking, then you can update the progress bar from your
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;
Apple continues to warn that networking on the main thread is bad.

Switch from Synchronous request to Asynchronous request with image upload?

I need some help, i have been searching around and cant find the correct answer im looking for.
I am uploading images and videos to my server via php, When im uploading the video or image, i want to be able to show a progress view, i have been told that the only way to do this is to use asynchronous instead of synchronous. I have been looking at ways to set up this, but cant really seem to find a good tutorial that will help me with what im trying to accomplish.
Here is some code:
- (void)post:(NSData *)fileData
{
NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:[self saveUserLogin]];
int test;
NSString *string = [array objectAtIndex:3];
test = [string intValue];
test++;
NSData *videoData = fileData;
NSString *urlString = [[NSString alloc]initWithFormat:#"http://www.site.com/members/uploadMovie.php?&username=%#", [array objectAtIndex:0]];
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]];
NSString *postName = [[NSString alloc]initWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"vid%i.mov\"\r\n", test];
[body appendData:[[NSString stringWithString:postName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
NSArray *values = [[NSArray alloc] initWithObjects: [array objectAtIndex:0],[array objectAtIndex:1], [array objectAtIndex:2], [NSString stringWithFormat:#"%i", test], nil];
[values writeToFile:[self saveUserLogin] atomically:YES];
[self.delegate didFinishController:self];
}
this is some code that im using to send a video. filedata is a paramater being passed in with the video data. I want to animate a UIProgressview for the upload progress. I have also heard that apple likes people to use asynchronous anyways. If someone could please help me set up asynchronous instead of what i have, i would be really grateful. Please be specific if you reply, like to what i need to import what delegates, methods. etc.
Thank you very much :)
EDIT:
This is what it looks like now:
- (void)post:(NSData *)fileData
{
NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:[self saveUserLogin]];
int test;
NSString *string = [array objectAtIndex:3];
test = [string intValue];
test++;
NSData *videoData = fileData;
NSString *urlString = [[NSString alloc]initWithFormat:#"http://www.site.com/members/uploadMovie.php?&username=%#", [array objectAtIndex:0]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
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]];
NSString *postName = [[NSString alloc]initWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"vid%i.mov\"\r\n", test];
[body appendData:[[NSString stringWithString:postName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
//NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(#"connected");
responceData = [NSMutableData data];
}
else{
NSLog(#"error");
}
// NSLog(#"%#", returnString);
NSArray *values = [[NSArray alloc] initWithObjects: [array objectAtIndex:0],[array objectAtIndex:1], [array objectAtIndex:2], [NSString stringWithFormat:#"%i", test], nil];
[values writeToFile:[self saveUserLogin] atomically:YES];
// [self.delegate didFinishController:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responceData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString* responseString = [[NSString alloc] initWithData:responceData encoding:NSUTF8StringEncoding];
NSLog(#"result: %#", responseString);
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"error - read error object for details");
}
NSUrlConnection has an asynchronous request with callbacks.
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest
NSUrlConnection overview:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
That doc also points out you can get an estimation of upload progress by implementing a callback.
connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
Estimating Upload Progress
You can estimate the progress of an HTTP POST upload with the
connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
delegate method. Note that this is not an exact measurement of upload
progress, because the connection may fail or the connection may
encounter an authentication challenge.

Full Quality For Video Upload

Im picking a video from UIImagePicker, the video is then being uploaded to my server. I want the quality of the video to remain the same. As of right now the video has a bit less quality compared to the one i took directly off my phone, and it is a smaller resolution.
here is my code:
-(IBAction)video:(id)sender{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
picker.allowsEditing = YES;
picker.wantsFullScreenLayout = YES;
picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
[self presentModalViewController:picker animated:YES];
}
- (NSData *)generatePostDataForData:(NSData *)uploadData
{
// Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\"; filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
[postData appendData: uploadData];
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
- (void)post:(NSData *)fileData
{
NSData *videoData = fileData;
NSString *urlString = #"http://www.site.com/scripts/upload.php";
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=\"userfile\"; filename=\".mov\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissModalViewControllerAnimated:YES];
//assign the mediatype to a string
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//check the media type string so we can determine if its a video
NSLog(#"got a movie");
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
[self post:webData];
}
setting the pickers quality to high i thought would do it, i guess not. I have the option to export in 720p, but i want iphone 4s's to upload in full 1080p.
Any help would be great. Thanks :D
You can't skip the annoying compression step, UIImagePicker insists on doing it. You can get at the high quality video by using the UIImagePickerControllerReferenceURL key, however the long compression step is a deal breaker for me.
So go log a bug, then check out this excellent drop in replacement.