how to pass parameter to NSMutableURLRequest object? - ios5

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;
}

Related

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.

How to POST an audio file via NSURLConnection iPhone?

I tried a dozen things. But am not receiving results. I want to convert an audio file wav/mp3 to byte array or otherwise and send it to a php server. Following are few things i tried that are already listed in SO. please help.
NSURL *urlPath = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"r2d2" ofType:#"mp3"]];
NSString *wavbundlepath = [urlPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:wavbundlepath]];
NSUInteger len = data.length;
int8_t *bytes = (int8_t *)[data bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:len];
[result appendString:#"["];
for (NSUInteger i = 0; i < len; i++) {
if (i) {
[result appendString:#","];
}
[result appendFormat:#"%d", bytes[i]];
}
[result appendString:#"]"];
NSString *urlString = #"http://apps2.mobiiworld.com/staging/krafttesting/";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData* dataSend = [result dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:dataSend];
NSURLResponse *response;
NSError *err;
NSData *responseData2 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData2);
next
NSURL *urlPath = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"r2d2" ofType:#"mp3"]];
NSString *wavbundlepath = [urlPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:wavbundlepath]];NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *filename = #"file";
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"%#\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
// NSLog([NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"%#\"\r\n", filename]);
//[body appendData:[[NSString stringWithString:#"test"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[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
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Return : %#", returnString);
The php developer says that he is not receiving any data whatsoever. And he has echoed whatever he receives, but i find a Null string in response. Can anyone please suggest what to do?
This is how i am doing it
NSData *audioData = Here comes your NSData;
NSString *urlString = #"The url of php file";
NSMutableURLRequest *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"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".caf\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:audioData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"Length : %d", returnData.length);
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Return String %#", returnString);
There is another way via ASIHTTPRequest
NSURL *url = [NSURL URLWithString:#"the url comes here"];
ASIFormDataRequest *formRequest = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
NSData *imageData = UIImageJPEGRepresentation([self scaleAndRotateImage:self.m_ImageViewProfile.image], 90);
NSLog(#"Size : %d", imageData.length);
[formRequest setTimeOutSeconds:600];
[formRequest setPostValue:#"If there is any"] forKey:#"the key"];
[formRequest setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"filename"];
//[formRequest setUploadProgressDelegate:progressView];
[formRequest setCompletionBlock:^{
NSString *responseString = [formRequest responseString];
NSLog(#"Response: %#", responseString);
}];
[formRequest setFailedBlock:^{
NSError *error = [formRequest error];
NSLog(#"Error: %#", error.localizedDescription);
}];
[formRequest startSynchronous];
See if it is what you want

uploading image to json server sending null NSUrlRequest

I am trying to upload the image to json server but url request is going null. Below is the code i am using.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *imageToScale=[info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *img = imageToScale;
//NSLog(#"finalImage---------------------------------%#",self.finalImage);
NSData *imageData = UIImageJPEGRepresentation(img, 0.40);
profileImg = profilePic;
NSArray *arrImg = [profileImg componentsSeparatedByString:#"/"];
NSString *strImg1 = [arrImg objectAtIndex:[arrImg count]-2];
NSString *strImg2 = [arrImg lastObject];
NSLog(#"img2-----------------%#",strImg2);
NSString *pImg = [NSString stringWithFormat:#"%#%#",strImg1, strImg2];
NSLog(#"img-----------------%#",pImg);
NSString *urlString = [NSString stringWithFormat:#"http://www.funnyghg.co/overheadPost.php?userId=%#&type=Photo&text=Demo test&image=%#&location=Chandigarh&Upload=Upload", uid, pImg];
NSLog(#"url :%#", urlString);
// setting up the request object now
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"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"1.jpg\"\r\n"] 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]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"returnString------------%#",returnString);
[self dismissModalViewControllerAnimated:YES];
[appDelegate showAllNavItems];
[appDelegate navFrame];
if([returnString isEqualToString:#"true"])
{
if([profile isEqualToString:#"friend"])
{
[self callServerFriend];
}
if([profile isEqualToString:#"public"])
{
[self callServerPublic];
}
}
}
Please guide for the above. Thanks in advance.
It is because in you code there is an space in urlString between Demo and test. Please remove it as.
Before :
NSString *urlString = [NSString stringWithFormat:#"http://www.funnyghg.co/overheadPost.php?userId=%#&type=Photo&text=Demo test&image=%#&location=Chandigarh&Upload=Upload", uid, pImg];
NSLog(#"url :%#", urlString);
After :
NSString *urlString = [NSString stringWithFormat:#"http://www.funnyghg.co/overheadPost.php?userId=%#&type=Photo&text=Demotest&image=%#&location=Chandigarh&Upload=Upload", uid, pImg];
NSLog(#"url :%#", urlString);
I hope it will work now.

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.