How to get Upload time remaining from Asynchronous Request? - iphone

I m trying to upload an Image from iPhone to Server. I m Able to Do so But i need to show an Indicator.My code is
NSData *imageData = UIImageJPEGRepresentation(newImage, 90);
// setting up the URL to post to
NSString *urlString = [NSString stringWithFormat:#"URL",[[formater stringFromDate:now] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithFormat:#"---------------------------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=\"image\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"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];
Here is the code to fire request.
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
}];
So How can i Calculate the Remaining time so that i can Show an indicator ?
Thanks for your time.

You can use this method of connection delegate:
- (void) connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;
(How should I wrap such long argument names?)
It's not in documentation of NSURLConnectionDataDelegate, but if you check the public header NSURLConnection.h, it's there. So don't worry about using it.
From documentation URL Loading System Programming Guide > Using NSURLConnection:
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.

I believe you want to show something like a progress bar. I recomend using the MKNetworkKit that provides you many tools for network management, such as progress of an asynchronous connection. Check this link.

Related

How can i record voice on my app and then send it to server?

Im trying to build an application that will record voices (mic) on my iPhone,
and then will send them to store on my server.
can anyone help me with this one.
i even don't know where to began with this :)
Thank you very much,
Oded.
Just google it "how to record iphone" and you get it in a seconds.
After recording, file will create in your Documents folder.
Retrieve that path and extract data in NSData and send to server through POST method.
Sample code,
NSLog(#"SendingRecordedData");
NSString *urlString = [NSString stringWithFormat:#"http://your_server/fileupload.php"];
NSLog(#"Url:%#",urlString);
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=\"pics\"; filename=\"record.caf\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data2]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
there is sample code with recording - SpeakHere on iOS developer site. After recording you can save it and send as any binary file.

what changes are needed in this code of upload image and get responce from server

- (IBAction) uploadImage {
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 100
*/
NSData *imageData = UIImageJPEGRepresentation(image.image, 100);
// setting up the URL to post to
NSString *urlString = #"http://uploadhere.com/photos/iphone.php";
// setting up the request object now
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]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"q\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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]];
NSLog(#"here1");
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSLog(#"here2");
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"here3");
//NSLog(returnString);
//picText = rowZero.pickerLabel.text;
NSLog(#"here4");
rowZero.path = returnString;
//NSLog(rowZero.path);
}
I have taken this code from some example and I am using it in my application...but I don't know why it is showing me that image is not actually being uploaded...can anyone please tell me whats going wrong??
please change this
NSData *imageData = UIImageJPEGRepresentation(image.image, 100);
NSData *imageData = UIImageJPEGRepresentation(urimageRepresentation, 100);
to ur own image representaion

Multi-Part HTTP Request through xcode

i want to upload image,video and audio files to a server. I have read this thread on the similar topic but wasn't able to understand completely the flow of the code. It would be great if you can suggest me some sample code or tutorial to start with. I am using the following code to connect without any media to the server
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *url =[[NSString alloc]initWithFormat:#"%#",[NetworkConstants getURL]];
NSURL *theURL =[NSURL URLWithString:url];
[url release];
NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0.0f];
[theRequest setHTTPMethod:#"POST"];
NSString *theBodyString = [NSString stringWithFormat:#"json1=%#&userID=%#",jsonObject,[GlobalConstants getUID]];
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:theBodyData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (conn) {
NSLog(#"Successful in sending sync");
}
else {
NSLog(#"Failed Connection in sending sync");
}
[conn release];
It would be really convenient for me if anything could be done editing this part of code.
Any form of help would be highly appreciated.
Thanks in advance!!
Although it is very early to answer my own question but I got the solution so thought of adding it up here.
To the above code we just need the following modification
NSData *imageData = UIImageJPEGRepresentation(attachedImage.image, 90);
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[theRequest addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *theBodyData = [NSMutableData data];
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[#"Content-Disposition: form-data; name= \"server_value_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[yourString dataUsingEncoding:NSUTF8StringEncoding]];
//this appends the image data
[theBodyData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"image\"; filename=\"1.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[[NSString stringWithString:#"Content-Type: image/jpg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[NSData dataWithData:imageData]];
[theBodyData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPBody:theBodyData];
And the rest remains the same as in Question.
One just need to remember while sending a Multi-Part Request that all the parameters required by the server need to go with in the boundary and every parameter should be send in individual boundaries.
Hope this helps the others as well.
:)

examples/tutorials iPhone post/upload request?

I am doing some uploading stuff in iphone this time. This is absolutely first time for me.
I have found some useful links and answers by googling and finding them on stackoverflow.
And I was able to upload an image by the following code :
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
NSString *urlString = #"server-url";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]init] autorelease];
[request setTimeoutInterval:60.0];
[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=\"file\";filename=\"myfile.jpg\"\r\n"]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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]];
//NSString * dataLength = [NSString stringWithFormat:#"%d", [body length]];
//[request addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
NSLog(#"%#",[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding]);
But I have lots of questions on the how the above code works like what is boundary and what is the format for it What is content disposition and other things as well .
I have googled a lot for understanding the format for a post request but found nothing then ready code If anyone knows some good tutorial or exmples on how a post request format is build in iphone then please provide so i can understand how the above code will work ?
you can look at the documentation on returning values from forms with POST here.
https://www.rfc-editor.org/rfc/rfc2388
like you said, the code works, this is a document explaining what you see and what it all means

iPhone : upload image to web aspx file

I have a little problem.
I have to upload a photo from my iPhone to a web server with POST Method but the server file is in aspx.
I tried my code with my server and PHP file : works well !
Now with aspx file : doesn't upload :(
I don't havec access to the .aspx .
Here is my iphone code :
NSData *imageData = UIImageJPEGRepresentation(imageView.image,70);
NSString *urlString = #"http://iphone.domain.net/upload_photos.aspx";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"photo\"; filename=\"%#.jpg\"\r\n",[c nom]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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];
I think the problem comes from the Content-Type or for my dataUsingEncoding: parameter.
Have you got and idea to solve it?
If you're not opposed to using a 3rd party library consider looking at ASIHttpRequest. It'll make your life so much easier:
http://allseeing-i.com/ASIHTTPRequest/
http://allseeing-i.com/ASIHTTPRequest/How-to-use
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"];
normally, the boundary does not contain the --- when it's specified in the Content-Type. Apart from that, can't see anything unusual.
Try to upload it to the aspx server from the command line with curl. Once you've got that working, pass -v (verbose) or -i (include HTTP headers) to check exactly what is being sent, and then you can try to replicate that in Cocoa.