Reputation: 1878
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.
Upvotes: 0
Views: 644
Reputation: 6166
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 .
To get the implementation of NSUrlConnection you can go through the
Url With Special Characters:-
[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Upvotes: 2