URL Connection: What is the difference between the following? - iphone

I need to know the difference between the following two methods of url connection?
What is the significance of these two methods?
Which method is preferred in what circumstances?
Method 1:
file.h
#import
#define kPostURL #"http://localhost/php/register.php"
#define kemail #"email"
#define kpassword #"password"
#interface signup : UIViewController
{
...
...
NSURLConnection *postConnection;
}
#property ...
...
#end
file.m
NSMutableDictionary *input=[[NSMutableDictionary alloc]init];
...
...
...
NSMutableString *postString = [NSMutableString stringWithString:kPostURL];
[postString appendString: [NSString stringWithFormat:#"?%#=%#", kemail, [input objectForKey:#"email"] ]];
[postString appendString: [NSString stringWithFormat:#"&%#=%#", kpassword, [input objectForKey:#"password"] ]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
[request setHTTPMethod:#"POST"];
postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSLog(#"postconnection: %#", postConnection);
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: postString ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"serverOutput = %#", serverOutput);
Method 2:
NSString *post =[NSString stringWithFormat:#"email=%#&password=%#",[input objectForKey:#"email"], [input objectForKey:#"password"]];
NSString *hostStr = #"http://localhost/frissbee_peeyush/php/login.php?";
hostStr = [hostStr stringByAppendingString:post];
NSLog(#"HostStr %#",hostStr);
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"serverOutput %#", serverOutput);
What if i need to connect to url only using header information ?
Problem: for login and signup, these methods are perfectly fine but whenever i want to insert any string containing special characters such as #,/,_ etc, it is unable to perform any operation.
Guide me plz.

Even the method 1 you have implemented is incomplete as there are many delegates of NSUrlConnection which should be implemented to get the data , handling errors , proxy , authentication etc . It is more advisable to use the first method but not in the way you used.NSUrlConnection in asynchronous in behaviour so You Don't have to wait until the url is loaded.
NSUrlConnection Class Reference
The Second method simply hits the url as sson as it encounters the NSUrl parameter in the NSData . Moreover , you don't have much control over your web service interaction .
NSUrl Class Reference
To get the implementation of NSUrlConnection you can go through the
NSUrlConnection Tutorial
Url With Special Characters:-
[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Related

How to upload data from iphone app to mysql data base

I have a EMR app and i want that i may send the data which i have collected like images and voice to server. in data base so how can i do this . Is there any way to send these data to server through post method.
Here is an example of a HTTP Post request
// define your form fields here:
NSString *content = #"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com/form.php"]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
Might want to reference http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSURLConnection_Class/Reference/Reference.html
This tutorial is also helpful http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service
In that case, you can do follow two ways:
1. if you strictly like to using POST (i like), u can using cocoahttpserver project:
https://github.com/robbiehanson/CocoaHTTPServer
In iphone app, you can do this code to send POST request:
-(NSDictionary *) getJSONAnswerForFunctionVersionTwo:(NSString *)function
withJSONRequest:(NSMutableDictionary *)request;
{
[self updateUIwithMessage:#"server download is started" withObjectID:nil withLatestMessage:NO error:NO];
NSDictionary *finalResultAlloc = [[NSMutableDictionary alloc] init];
#autoreleasepool {
NSError *error = nil;
NSString *jsonStringForReturn = [request JSONStringWithOptions:JKSerializeOptionNone serializeUnsupportedClassesUsingBlock:nil error:&error];
if (error) NSLog(#"CLIENT CONTROLLER: json decoding error:%# in function:%#",[error localizedDescription],function);
NSData *bodyData = [jsonStringForReturn dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataForBody = [[[NSData alloc] initWithData:bodyData] autorelease];
//NSLog(#"CLIENT CONTROLLER: string lenght is:%# bytes",[NSNumber numberWithUnsignedInteger:[dataForBody length]]);
NSString *functionString = [NSString stringWithFormat:#"/%#",function];
NSURL *urlForRequest = [NSURL URLWithString:functionString relativeToURL:mainServer];
NSMutableURLRequest *requestToServer = [NSMutableURLRequest requestWithURL:urlForRequest];
[requestToServer setHTTPMethod:#"POST"];
[requestToServer setHTTPBody:dataForBody];
[requestToServer setTimeoutInterval:600];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[urlForRequest host]];
NSData *receivedResult = [NSURLConnection sendSynchronousRequest:requestToServer returningResponse:nil error:&error];
if (error) {
NSLog(#"CLIENT CONTROLLER: getJSON answer error download:%#",[error localizedDescription]);
[self updateUIwithMessage:[error localizedDescription] withObjectID:nil withLatestMessage:YES error:NO];
[finalResultAlloc release];
return nil;
}
NSString *answer = [[NSString alloc] initWithData:receivedResult encoding:NSUTF8StringEncoding];
JSONDecoder *jkitDecoder = [JSONDecoder decoder];
NSDictionary *finalResult = [jkitDecoder objectWithUTF8String:(const unsigned char *)[answer UTF8String] length:[answer length] error:&error];
[finalResultAlloc setValuesForKeysWithDictionary:finalResult];
[answer release];
[self updateUIwithMessage:#"server download is finished" withObjectID:nil withLatestMessage:NO error:NO];
if (error) NSLog(#"CLIENT CONTROLLER: getJSON answer failed to decode answer with error:%#",[error localizedDescription]);
}
NSDictionary *finalResultToReturn = [NSDictionary dictionaryWithDictionary:finalResultAlloc];
[finalResultAlloc release];
return finalResultToReturn;
}
Don't forget to pack attributes with images to base64.
Finally, if u don't like to keep data, which u send in you mac app, u can send to u database using any database C api. I recommend to using core data to save receive data.

Passing URL with parameter

I am passing url with some string value and NSInteger value in this url but when I put breakpoint on this and I tab on trace then it show me this message exc-bad-access in url I given bold please see that 'bold' I want to pass there value:
[ NSInteger day,NSInteger day1,NSString *fromDate1, NSString *fromDate1,NSString *OriginCode,NSString *DestinCode].
I get all value on url when I put the breakpoint but when I step into breakpoint my app crashes, why it crash? Help me. Where am I wrong?
-(void)sendRequest
{
stringWithFormat:#"http://www.google.com?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySeast=",day,day1,DestinCode,"2011-09","2011-09",OriginCode];
NSString *urlString = [NSString stringWithFormat:#"http://www.bookairways tickt.com/Sales/FRSearch.aspx?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay1=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay2=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDestination1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth2=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketOrigin1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_ADT=1&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_CHD=0&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_INFANT=0&AvailabilitySearchInputFRSearchView%24RadioButtonFlowSelector=FlightAndCar&AvailabilitySearchInputFRSearchView%24RadioButtonMarketStructure=RoundTrip&AvailabilitySearchInputFRSearchView%24discountPax=0&__EVENTARGUMENT=&__EVENTTARGET=&__VIEWSTATE=%2FwEPDwUBMGRkg4UKvNNb1NbM14%2F2n9zUxhNQ%2B%2BA%3D&errorlist=",day,day1,DestinCode,fromDate1,fromDate2,OriginCode];
//urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"************url:%#",url);
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
} else {
}
}
make your url properly like this:-
NSURL *url = [NSURL URLWithString:[*yourstring* stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Harish this will help u to in creating the url check this our http://wiki.akosma.com/IPhone_URL_Schemes
like this
NSString *template = #"appigotodo://com.example.xyzapp/import?name=%#&note=%#&due-date=%#&priority=%#&repeat=%#";
NSString *name = #"Buy%20some%20milk";
NSString *note = #"Stop%20on%20the%20way%20home%20from%20work.";
NSString *dueDate = #"2009-07-16";
NSString *priority = #"1";
NSString *repeat = #"101";
NSString *stringURL = [NSString stringWithFormat:template, name, note, dueDate, priority, repeat];
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
Two things:
The URL has many % symbols that are not being used as placeholders. The % symbols that are not between '**' in your code need to be escaped like so: %%. In other words, SearchInputFRSearchView%24Button should be SearchInputFRSearchView%%24Button.
You are using %i to put integers into your string. You should be using %d instead.

Iphone dev : how can I get a result from google currency converter?

Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.
I have already tried something like that :
-(IBAction)getResponse:(id) sender{
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil && data != ""){
NSString *response = [[[NSString alloc] initWithData:data]]
[label setText: response];
}
else [label setText:#"not working"];
}
But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.
Yeah.. It is possible...
See the data that you are getting is an HTML file or can be treated as xml. Just parse that xml file and get the result. There ia lot of things in that file but you have to only extract
<div id=currency_converter_result>1 USD = <span class=bld>0.6118 GBP</span>
Hey try this URL
http://www.google.com/ig/calculator?hl=en&q=1USD=?INR
This URL will return the JSON
{lhs: "1 U.S. dollar",rhs: "44.5097254 Indian rupees",error: "",icc: true}
Just parse it. :)
Try...
NSData *data = [[NSData alloc] init];
Then check you've got something in response
NSLog(#"%#", response);
Better yet, remove the NSData alloc/init
Replace with
 
NSData *data=[NSData dataWithContentsOfURL:myURL];
And, you'll need to parse the return result, because you're not going to get back what you expect. Response will contain HTML page.
You better use an asynchronous request to avoid blocking your app. Easy using ASIHTTPRequest:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://www.google.com/finance/converter?a=1&from=USD&to=GBP"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
[label setText: responseString];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error]; //you can log the error description
[label setText:#"not working"];
}
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil){
NSString *response = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSLog(#"%#",response);
}
Try this.
This API is giving HTML responce.

How to post a string to web server url in iphone sdk?

How can I post a string(i.e) a word to web server url in iphone sdk?
Some sample codes or tutorials would be appreciated.
Thanking you.
This may help you, although I havent tested it:
NSMutableString *httpBodyString;
NSURL *url;
NSMutableString *urlString;
httpBodyString=[[NSMutableString alloc] initWithString:#"Name=The Big Bopper&Subject=Hello Baby&MsgBody=...You knooow what I like...Chantilly lace..."];
urlString=[[NSMutableString alloc] initWithString:#"http://www.somedomain.com/contactform.php"];
url=[[NSURL alloc] initWithString:urlString];
[urlString release];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[url release];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[httpBodyString dataUsingEncoding:NSISOLatin1StringEncoding]];
[httpBodyString release];
NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!connectionResponse)
{
NSLog(#"Failed to submit request");
}
else
{
NSLog(#"--------- Request submitted ---------");
NSLog(#"connection: %# method: %#, encoded body: %#, body: %a", connectionResponse, [urlRequest HTTPMethod], [urlRequest HTTPBody], httpBodyString);
NSLog(#"New connection retain count: %d", [connectionResponse retainCount]);
responseData=[[NSMutableData data] retain];
NSLog(#"response", responseData);
}
Source: http://www.iphonedevsdk.com/forum/iphone-sdk-development/6341-help-executing-http-url-post-variables.html
You can post the string to webservice in so many ways, In those one is
Using Rest protocol:
It has two sub types, HTTP GET, HTTP POST. The Http Get is simple.
You can add the value to the attribute and you can directly call the service.
Check the following code.
NSString *url = #"http://123.456.789.0?action=get_movies";
Here the I am passing the get_movies string to the server to the action attribute.
and then follow the code for requesting to server.
NSURL *reqUrl = [[NSURL alloc] initWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:reqUrl];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSStringEncoding responseEncoding = NSUTF8StringEncoding;
if ([response textEncodingName]) {
CFStringEncoding cfStringEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]);
if (cfStringEncoding != kCFStringEncodingInvalidId) {
responseEncoding = CFStringConvertEncodingToNSStringEncoding(cfStringEncoding);
}
}
[reqUrl release];
NSString *dataString = [[NSString alloc] initWithData:data encoding:responseEncoding];
the dataString is the responseString from the server. You can use that.
Regards,
Satya.

how to send a word/text to a php file from iphone application

I am trying to send a word/text from my iphone application to php page, any idea?
You might do it with an asynchronous call.
// Prepare the URL
NSString myWord = #"YOUR_WORD";
NSString *urlString = [NSString stringWithFormat:#"http://<YOUR_DOMAIN>/<YOUR_FILE>.php?word=%#", myWord];
NSURL *url = [NSURL URLWithString:urlString];
// Get the data from the URL
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
// If you want to get an answer from this call then send "self" as delegate
// (and implement few NSURLConnectionDelegate methods),
// otherwise send "nil".
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
You might also send the word synchronously:
// Prepare the URL
NSString myWord = #"YOUR_WORD";
NSString *urlString = [NSString stringWithFormat:#"http://<YOUR_DOMAIN>/<YOUR_FILE>.php?word=%#", myWord];
// Get the data from the URL
NSError *error;
NSData *aData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlString] options:2 error:&error];
You would just have to load the URL with the word / text as a parameter using NSURLConnection. See the following for help in using NSURLConnection:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836
And, some sample code:
// The word
NSString wrd = [NSString stringWithString:#"hello"];
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yourdomain.com/thepage.php?word=#%", wrd]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}