iphone: didReceiveAuthenticationChallenge and canAuthenticateAgainstProtectionSpace are not called for secure restful service - iphone

I am trying to get data from a secure restful service. I follow many other posts alongwith
How to use NSURLConnection to connect with SSL for an untrusted cert?
But in my case didReceiveAuthenticationChallenge and canAuthenticateAgainstProtectionSpace are not get called.
please help if you could solve the problem or provide me some good example to call secure restful service.
NSURL *url = [NSURL URLWithString:#"https://76.69.53.126:8443/jaxrs/tdgateway/getCountries"];
NSError * error = nil;
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[ NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: &error ];
NSLog(#"This is %#",url);
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
NSLog(#"This is canAuthenticateAgainstProtectionSpace");
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(#"This is didReceiveAuthenticationChallenge");
[[challenge sender] cancelAuthenticationChallenge:challenge];
}

It could be different than NSURLAuthenticationMethodServerTrust, so just try this to start:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
You should not cancel it immediately:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(#"This is didReceiveAuthenticationChallenge");
[[challenge sender] cancelAuthenticationChallenge:challenge];
}

NSString *XAPIKEY = #"myapikey";
NSString *LOGINUSER = #"login username";
NSString *LOGINPASS = #"passwords";
// Setup NSURLConnection
- (void) postRequest:(NSString *) requestFun requestData:(NSDictionary *) sendDataDic{
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", #"http://api.domain.com/index.php/api/", requestFun]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:XAPIKEY forHTTPHeaderField:#"X-API-KEY"];
if(sendDataDic != nil){
NSString *stringData = [self urlEncodedString:sendDataDic];
[request setHTTPBody:[stringData dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[stringData length]] forHTTPHeaderField:#"Content-Length"];
}
[request setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void) getRequest:(NSString *) requestFun requestData:(NSDictionary *) sendDataDic{
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", #"http://api.domain.com/index.php/api/", requestFun]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:XAPIKEY forHTTPHeaderField:#"X-API-KEY"];
if(sendDataDic != nil){
NSString *stringData = [self urlEncodedString:sendDataDic];
[request setHTTPBody:[stringData dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[stringData length]] forHTTPHeaderField:#"Content-Length"];
}
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
static NSString *toString(id object) {
return [NSString stringWithFormat: #"%#", object];
}
static NSString *urlEncode(id object) {
NSString *string = toString(object);
return [string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
}
-(NSString*) urlEncodedString:(NSDictionary*) ObjDic {
NSMutableArray *parts = [NSMutableArray array];
for (id key in ObjDic) {
id value = [ObjDic objectForKey: key];
NSString *part = [NSString stringWithFormat: #"%#=%#", urlEncode(key), urlEncode(value)];
[parts addObject: part];
}
return [parts componentsJoinedByString: #"&"];
}
// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSLog(#"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:LOGINUSER
password:LOGINPASS
persistence:NSURLCredentialPersistenceForSession];
NSLog(#"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(#"responded to authentication challenge");
} else {
NSLog(#"previous authentication failure");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"response status code: %ld", (long)[httpResponse statusCode]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", strData);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"responded to authentication challenge");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"responded to authentication challenge");
}

Related

bigcommerce api on iphone

i am using bigcommerce api in iphone to fetch data from that so i am doing it with the help of xml parsing but to get the list of orders it is asking for the login into bigcommerce website and then parse the data if anyone help me in this then i will be very thankful , please tell me through xml parsing how we can send login credentials and then hit on the url to parse data.....
thankyou
i am writing this code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Add the navigation controller's view to the window and display.
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];
// Override point for customization after application launch.
NSString *string=[NSString stringWithFormat:#"https://www.labradorhometraining.com/api/v2"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:string]];
// NSString *dataString = [NSString stringWithFormat:#"{\"screenName\":\"%#\",\"password\":\"%#\",\"pushToken\":\"%#\",\"deviceType\":\"%#\"}", Screentxtf.text,passtxtf.text, str, deviceType];
[request setRequestMethod:#"GET"];
[request appendPostData:[string dataUsingEncoding:NSUTF8StringEncoding]];
// Basic YWRtaW46cGFzc3dvcmQ=
[request addRequestHeader:#"Content-Type" value:#"application/xml"];
[request addRequestHeader:#"Authorization: Basic ZGVtb2tleTpkZW1vdG9rZW4= " value:[NSString stringWithFormat:#"%# %#",#"api", #"c275ab4076f87"]];
[request setUseSessionPersistence:NO];
[request setUseCookiePersistence:NO];
[request setCacheStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
[request setDelegate:self];
[request startAsynchronous];
return YES;
}
and this is in root view controller
-(void)gototselect{
NSString *string=[NSString stringWithFormat:#"https://www.labradorhometraining.com/api/v2/orders.xml"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:string]];
// NSString *dataString = [NSString stringWithFormat:#"{\"screenName\":\"%#\",\"password\":\"%#\",\"pushToken\":\"%#\",\"deviceType\":\"%#\"}", Screentxtf.text,passtxtf.text, str, deviceType];
[request setRequestMethod:#"PUT"];
// [request appendPostData:[string dataUsingEncoding:NSUTF8StringEncoding]];
[request addRequestHeader:#"Authorization" value:[NSString stringWithFormat:#"%# %#",#"api", #"c2714076f87"]];
[request allowCompressedResponse];
[request setUseSessionPersistence:NO];
[request setUseCookiePersistence:NO];
[request setCacheStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
[request setDelegate:self];
[request startAsynchronous];
}
I don't have any idea about ASIHTTPRequest API and also i never used it my career. But using plain objective-C i share some code for how do you authenticate http request,
// Setup NSURLConnection
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[connection release];
// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSLog(#"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:#"USER"
password:#"PASSWORD"
persistence:NSURLCredentialPersistenceForSession];
NSLog(#"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(#"responded to authentication challenge");
}
else {
NSLog(#"previous authentication failure");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
...
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
...
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
...
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
...
}
the above code i copied from NSURLConnection and Basic HTTP Authentication in iOS this link.
Also i want to share some more link with you. Refer apple doc for HTTP request http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html
And this post http://www.cocoanetics.com/2010/12/nsurlconnection-with-self-signed-certificates/ .. you will get lot of information and tactics about this work.

Not getting server response string after successfully server response and successfully database insert

- (void)viewDidLoad
{
[super viewDidLoad];
NSString *jString = #"{\"block_face_line\" : [{\"longitude\" : -71.34345555,\"latitude\" : 42.7794343 },{\"longitude\" : -71.4473179666667,\"latitude\" : 42.7336227666667 }, {\"longitude\" : -71.4461721166667,\"latitude\" : 42.7321493333333 },{\"longitude\" : -71.4473179662267,\"latitude\" : 42.726227666667 } ],\"block_face_curb_side\" : \"LEFT\",\"block_face_collector_id\" : \"3\"}";
NSLog(#"JSON : : : : %#",jString);
NSURL *passurl = [NSURL URLWithString:[[NSString stringWithFormat:#"https://XXXX:XXXX#parkme.goldenware.com/cgi-bin/db.test?COMMAND=add&TABLE=block_faces&USER=1&SUBSYSTEM=json"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"passurl:%#",passurl);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:[passurl absoluteString]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
NSLog(#"request:%#",request);
mFinalData = [jString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jString length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:mFinalData];
receivedData = [[NSMutableData alloc] init];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
NSLog(#"Connection = %#", connection);
if(connection)
{
self.receivedData = [[NSMutableData data] initWithCapacity:2048];
NSLog(#"receive data:%#",self.receivedData);
NSString *stringData= [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog (#"result%#", stringData);
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection Failed To Response");
self->operationFailed = YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// if (!operationBreaked)
// [self.receivedData appendData:data];
// else
// {
// [connection cancel];
// NSLog(#" STOP !!!! Receiving data was stoped");
// }
NSLog(#"DONE1111");
[receivedData appendData:data];
NSLog(#"didreceivedata:%#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"[DO::didReceiveData] %d operation", (int)self);
NSLog(#"[DO::didReceiveData] ddb: %.2f, wdb: %.2f, ratio: %.2f",
(float)bytesReceived,
(float)expectedBytes,
(float)bytesReceived / (float)expectedBytes);
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
NSLog(#"Received status code: %d %#", [(NSHTTPURLResponse *) httpResponse statusCode],
[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse *) httpResponse statusCode]]) ;
}
NSLog(#"soapMsg1: %d", [receivedData length]);
[receivedData setLength:0];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [receivedData length]);
NSString *theXML = [[NSString alloc] initWithBytes:[receivedData mutableBytes] length: [receivedData length] encoding:NSUTF8StringEncoding];
NSLog(#"theXML:%#",theXML);
connection = nil;
receivedData =nil;
operationFinished = YES;
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
//
// connection:didReceiveAuthenticationChallenge:
//
// Show the authentication challenge alert to the user (or gives up if the
// failure count is non-zero).
//
- (void)connection:(NSURLConnection *)aConnection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)aChallenge
{
[aChallenge.sender useCredential:[NSURLCredential credentialForTrust:aChallenge.protectionSpace.serverTrust] forAuthenticationChallenge:aChallenge];
NSLog(#"Challenge Protection Space = %#",aChallenge.protectionSpace.host);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Getting server response 200 but not getting response string, response from server should be like:
// Status Code : OK , Status Description : OK ID=77
Or only ID number, for Example: `123`
Where is receivedData defined? Is it an ivar? What does your logging look like in -connection:didReceiveData:? Does recievedData show data in the log there? If so, what's clearing it by the time you get to -connectionDidReceiveResponse:?
In all likelihood, either receivedData isn't defined properly so is always nil, or isn't being retained properly, so it's being dealloc'd before you get to -connectionDidReceiveResponse:

iPhone authentication process

I have trouble finding info on this topic. Please help me out here.
I need to pass arguments via POST or GET method to my web server and get a reply.
Basically, if using GET method, I want to do something like server.com/?user=john&password=smith and receive the dynamically generated HTML code that is done with my php script. All this without using the web browser on my app.
How is it usually done?
You'll want to look into NSMutableURLRequest and NSURLConnection.
For example, you could use them like this do to a GET request to your server:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// GET
NSString *serverURL = [NSString stringWithFormat:#"http://yourserver.com/login.php?user=%#&pass=%#", username, password];
NSURL *url = [NSURL URLWithString:serverURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
This will send an asynchronous GET request to your server with the query string containing username and password.
If you want to send username and password using a POST request, the method would look something like this:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// POST
NSString *myRequestString = [NSString stringWithFormat:#"user=%#&pass=%#",username,password];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSURL *url = [NSURL URLWithString:#"http://yourserver.com/login.php"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod: #"POST"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[req setHTTPBody: myRequestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
In order to get the response from the server, you will need to implement the NSURLConnection delegate methods, for example:
#pragma mark -
#pragma mark NSURLConnection delegate methods
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
// Called if you have an .htaccess auth. on server
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"your_username" password:#"your_password" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[connectionData setLength: 0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[connectionData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connectionData release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[connectionData bytes]
length:[connectionData length] encoding: NSUTF8StringEncoding];
// This will be your server's HTML response
NSLog(#"response: %#",content);
[content release];
[connectionData release];
}
References:
NSMutableURLRequest Class Reference
NSURLConnection Class Reference
Hope this helps :)
Usually this is done using a NSURLConnection. You can also use NSString's method stringWithContentsOfURL.

How to download docx , pdf , image , pptx , or any file from a internet

How to download docx , pdf , image , pptx , or any file from a site which ask for credentials for authentication i tried passing the credentials and still data in the nsdata is something else but it store that detain the file created locally can anybody help in the code for downloading any kind of file.
the code is as follows:
in this buttonClicked is called from other file
DownloadingFile.h
#import "MyAppDelegate.h"
#interface DownloadingFile : NSObject
{
NSMutableData *webData;
NSMutableString *soapResults;
NSURLConnection *conn;
BOOL *elementFound;
BOOL isDoneParsing;
MyAppDelegate *mydelegate;
NSString *userCd,*passWord,*siteUrl;
}
#property (nonatomic ,retain) MyAppDelegate *mydelegate;
-(void)buttonClicked;
-(bool)getIsDone;
#end
DownloadingFile.m
#import "DownloadingFile.h"
#import "iExploreAppDelegate.h"
#implementation DownloadingFile
#synthesize mydelegate;
- (void)buttonClicked
{
mydelegate=(MyAppDelegate *)[[UIApplication sharedApplication] delegate];
userCd=[[NSString alloc] initWithString:[mydelegate getUserId]];
passWord=[[NSString alloc] initWithString:[mydelegate getPassword]];
NSLog(#"In Downloading; ");
NSURL *url =[NSURL URLWithString:[#"http://abcdef.xyz.com/Docs/NewFolder/myFile.docx" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setValue:[NSString stringWithFormat:#"bytes=%ld-",0] forHTTPHeaderField:#"Range"];
[req addValue: #"docx" forHTTPHeaderField:#"Content-Type"];
[req setHTTPMethod:#"POST"];
//---set the headers---
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
if (conn) {
NSLog(#"connection done ");
webData = [[NSMutableData data] init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential=[NSURLCredential credentialWithUser:userCd password:passWord persistence:NSURLCredentialPersistenceNone];
NSLog(#"Crediantials done ");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSError* error = [NSError errorWithDomain:#"SoapRequest" code:403 userInfo: [NSDictionary dictionaryWithObjectsAndKeys: #"Could not authenticate this request", NSLocalizedDescriptionKey,nil]];
NSLog(#"Credentials are not valid");
[mydelegate loginFailled:false];
}
}
-(void) connection:(NSURLConnection *) connection
didReceiveResponse:(NSURLResponse *) response {
//[webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection
didReceiveData:(NSData *) data {
NSLog(#"recevied data %#",data);
webData=[NSMutableData dataWithData:data];
[webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection
didFailWithError:(NSError *) error {
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"Did Finish Loading done ");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"FileName.docx"];
[webData writeToFile:pdfPath atomically:YES];
[connection release];
}
I just wrote a quick app to test using Apple's NSURLConnection which is both a simple and robust solution. I downloaded a few hundred KB Word and PowerPoint files. For authentication I used .htaccess. Works like a charm. Here is the relevant code.
- (IBAction)clickedDownload:(id)sender {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://myserver.com/downloadTest/testfile.pptx"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// inform the user
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"theUsername"
password:#"thePassword"
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential
forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
// inform the user that password is incorrect
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
receivedData = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSURL *docDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *filePath = [docDirectory URLByAppendingPathComponent:#"testfile.pptx"];
[receivedData writeToURL:filePath atomically:YES];
[receivedData release];
connection = nil;
}
Now I opened the files in ~/Library/Application Support/iPhone Simulator/4.3.2/Applications/[unique-application-code]/Documents- works great!
You should look into ASIHTTPRequest.
http://allseeing-i.com/ASIHTTPRequest/How-to-use
NSURL *url = [NSURL URLWithString:#"http://abcdef.xyz.com/Docs/NewFolder/myFile.docx"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:#"username"];
[request setPassword:#"password"];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
- (void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
}
- (void)requestWentWrong:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}

Send HTTP request in objective c

I need to connect to a server without typing "http://". I have to get only the server name and port number from the user. With this, I should be able to connect to a particular server...
In its simplest form, it looks something like this:
- (void)loadHostName:(NSString *)hostName onPort:(NSInteger)portNumber {
responseData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#:%i", hostName, portNumber]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Oh noes! %#", [error localizedDescription]);
[responseData release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Do something with the data, like load it in a web view.
[webView loadData:responseData MIMEType:#"text/html" textEncodingName:#"utf-8" baseURL:nil];
[responseData release];
}
In production code, you should handle cache requests, authentication challenges etc. (see the messages on NSURLConnection), but the above example will send an HTTP request and load it into a web view.
Try this,
NSURL *aUrl = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#:%i", hostName, portNumber]];
NSURLRequest *request = [NSURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
NSString * theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
[resp release];
[err release];
NSLog(#"response: %#", theString);
well you can hardcode HTTP:// with the server name
example
NSString *serverName = "stackoverflow.com";
NSNumber *portNumber = 10;
NSString *finalYrl = [NSString StringWithFormat:#"HTTP://%#:%#",serverName , portNumber];