Pass username and password to webservice in iphone

There are different ways to pass username and password to connect webservice.
Username and password can be posted in the web service url itself to authenticate.
Suppose you have following information:
Webservice url: http://sitename.com
username: myusername
password: mypassword

then you can add your credential in web service url and new url will be:

http://myusername:mypassword@sitename.com

In iphone, you can do this using string manipulation.
See following:
NSString *upd = [NSString stringWithFormat:@"%@%@%@%@%@", @"://" , userName, @":",password, @"@"];
  upd =  [urlString stringByReplacingOccurrencesOfString:@"://" withString:upd] ;
  newUrlString =(NSMutableString *) upd;
The logic is to replace "://" to "://myusername:mypassword@" in the web service url. Now you can use this new url to NSMutableURLRequest object to call web service.

Hope, It helps.

No comments:

Post a Comment