image transfer between iPhone application and server - iphone

There are many kinds of parsing methods like NSXML , JSON etc etc.
I am confused with so many methods. So please help me out to choose out of them.
Which will be the best parsing method to be followed if images have to be retrieved from and uploaded to a remote server in an iPhone application??

ASIHTTPRequest to perform asynchronous requests.
JSON Framework to parse incoming JSON objects into native data objects (NSDictionaries and NSArrays).
UIImage *myDownloadedImage = [UIImage imageWithData:[requestObject responseData]]; to turn downloaded image data into a UIImage.
Here's some sample code from one of my recent projects. I've included ASIHTTPRequest.h and JSON.h.
NSString *projurl = [NSString stringWithFormat:#"%#mobile/project_details/?project=%#", WEBAPPURL, self.projectId];
__block ASIHTTPRequest *r = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:projurl]];
[r setCompletionBlock:^{
self.projectData = [[r responseString] JSONValue];
[self.tableView reloadData];
}];
[r startAsynchronous];
You could turn right around in that completion block, pick out image URLs associated with this project, request them, handle the response inside ANOTHER completion block nested inside the first one... The beauty of ASI's new block-oriented result handling is that it can all happen in one place, and you don't have to sweat the details of a formal delegate pattern.
You could put up a "loading" UI element just before the startAsynchronous call, and remove it in the completionBlock, if you wanted.

Generally information coming from server will be in xml or JSON format.
NSXML parser parses xml data and JSON parser parses json data. But image will not be in xml or Json format. Image will be chunks of byte which you have to download from the server.
Generally , image url's can be part of xml or json data which will be parsed using appropriate parser . Once you get the url of image, you will use NSUrlConnection or ASIHttpRequest (library) to download the image.

Use XML to retrive list of images.(Store it on server or get it from web service)
Use NSXmlParser to parse and get image URL.
Use this for getting image. [NSData dataWithContentsOfURL:<#(NSURL *)url#>]
OR
Use following.
NSURL *url = [NSURL URLWithString:[fileUrl
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
webData = [[NSMutableData alloc] init];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest
delegate:self startImmediately:YES];
Or SOAP code
NSURL *url = [NSURL URLWithString:#"<URL>"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content- Type"];
[theRequest addValue: #"<ADD Value Here>" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection theConnection = [[NSURLConnection alloc] initWithRequest:theRequest
delegate:self startImmediately:YES];
In above if you are passing URL of file to some web service as request and it returns XML with with file data bound in it then parse it through NSXmlParser and in following method write data in file.
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
write here if you need any further assistance.

Related

json post request method

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *encodedString = [jsonString base64EncodedString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:encodedString forHTTPHeaderField:#"Data"];
This doesn't make sense. You're creating JSON, base-64 encoding it (you never have to base-64 encode JSON; if you were really trying to encrypt it, you have to come up with something better), and setting the header Data with this, while simultaneously providing a Content-Type informing the server that the request was XML, even though it wasn't.
If the server was expecting JSON, you'd just send JSON:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
If the server was expecting XML, you'd use the text/xml or application/xml setting for Content-Type, but you'd also (a) have to construct the XML content; and (b) supply that to setHTTPBody.
If you wanted to secure the request, you'd use https://.
Bottom line, you must confirm what precisely the server is looking for. Don't guess, but rather look at the server's source code or documentation or talk to the developers. But your client-side code sample is unlikely to work as it stands.

What I did is correct or not? When I send an audio file to server in NSData

I am recording audio in a .wav format and converting the .wav1 file to NSData and sending to server.
Recorded path is:
file://localhost/var/mobile/Applications/8F81BA4C-7C6F-4496-BDA7-30C45478D758/Documents/sound.wav
I am sending to the server using:
audioURL=#"file://localhost/var/mobile/Applications/8F81BA4C-7C6F-4496-BDA7-30C45478D758/Documents/sound.wav";
NSURL *url=[NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url];
[request setHTTPMethod: #"POST"];
[request setValue: #"multipart/form-data" forHTTPHeaderField: #"Content-Type"];
NSData *audiodata = [NSData dataWithContentsOfURL:audioURL];
NSMutableData *highScoreData = [NSMutableData data];
[highScoreData appendData:audiodata];
[request setHTTPBody:highScoreData];
nsurlConnection = [[NSURLConnection alloc] initWithRequest: request
delegate: self];
When I play this back it gives me the right recorded voice. However, when I play the same recorded voice from the server it says "quotation" instead of the actual recorded voice.
My full code of how I did audio recording and how i send the audio can be found here.
Please tell me if the way I did this(i.e, to sending to server) is correct or not?
Multipart requests don't work that way. You need boundaries to differ between different data. Please check: http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
For the solution, I use AFNetworking (https://github.com/AFNetworking/AFNetworking).
The AFHTTPClient can create multipart requests for you.
Check: http://afnetworking.github.com/AFNetworking/Classes/AFHTTPClient.html#//api/name/multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:
Here is the code I use to upload. The header part depends on how your server handles this.
AsiFormdata is more proper here.
NSString* fileString;
fileString = [[self documentsPath]
stringByAppendingPathComponent:#"testcombine.m4a"];
NSData* songData=[NSData dataWithContentsOfFile:fileString];
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://%#/UsingWebServer2/UploadServlet",RemoteEndpoint]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setData:songData withFileName:#"upload_test.m4a" andContentType:#"audio/m4a" forKey:#"file"];
//[request appendPostData:[Jstring dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
If you want to send the data via multipart/form-data, use ASIFormDataRequest. Find documentation here for more reference.

iPhone : How to fetch data from web service where web service uses "POST" method for JSON?

I want to fetch data from web service using JSON in my app.
Web service is developed in C# and it uses POST method to pass data.
I found one example but its useful only for GET method?
So How can I fetch JSON data where web service uses POST method?
And I also want to send data to web service. How can I do that ?
I'm sending POST request in following way (sending xml with some parameters).
NSString *message = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];
NSURL *url = [NSURL URLWithString:#"https://www.site.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[message length]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
[message release];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
To collect data you should implement method:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
where you should save received data.
In method:
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
you can parse that data with some JSON-parser.
Hope, that will help you. If you'll have questions about this code ask them in comments.

NSMutableURLRequest loses session information

I have an iphone app that I'm trying to get to talk to a rails back end. I'm using NSMutableURLRequest to pull data back and forth. All the calls work fine on GET requests but when I need to post data, my rails app can't seem to find the session. I've posted the code below for both a get and a POST request.
This is the POST request:
//Set up the URL
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/players.xml"];
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
//To create an object in rails
//We have to use a post request
////This is the format when using xml
NSString *requestString = [[NSString alloc] initWithFormat:#"<player><team_game_id>%#</team_game_id><person_id>%#</person_id></player>", game, person];
NSData *requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//For some reason rails will not take application/xml
[request setValue:#"application/xml" forHTTPHeaderField:#"content-type"];
The get request is:
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/people/find_by_passport?passport=%i", passport];
passportString = [[NSMutableString alloc] initWithFormat:#"%i", passport];
NSLog(#"The passport string is %#", passportString);
NSLog(url_string, nil);
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
I am at my wits end here trying to find out whats going on so any help would be GREATLY appreciated.
Faced the same issue. Parse the response headers for the Set-Cookie header, extract the cookies by hand, pass them back as Cookie: header on subsequent requests.
If this is just about sessions in their simplest, you don't have to worry about persistence, HTTPS, domains/paths and such.
EDIT: I found class NSHTTPCookieStorage. See if it can be of help...

How do I use UIActivity Indicator with NSUrlConnection

I'm using NSUrlConnection for accessing data from server.
I want that during fetching of the data from the server the user interactivity is stopped as well as the code execution.
And I read more and more on Stack Overflow or Google, but I'm not get appropriate solution.
Please see the code which I'm using.
The first time when the user clicks to access the data from the server I start the activity indicator.
[activity startAnimating];
NSString *post =
[[NSString alloc] initWithFormat:#"Email=%#&Pass=%#",Email,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://server.in/LoginStatus.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
}
and in the connectionDidFinishLoading function I stop the activity indicator.
The problem is that when I check the returned data then it displays the previous result. When clicked again it display the proper result.
Please suggest if you have any idea.
Try run the UIActivityIndicator and the NSURLConnection in different threads. I had the problem that the Indicator didn't show up when the Connection was alive. Putting both in seperate Threads solved it.
Just use
[activity startAnimating];
within your method
now try to make the NSURL Connection in some thread.And call the thread from your method
and once the connection get Finish use
[activity stopAnimating];
Will definitely work