Currently I am loading an image from URL in my iPhone app, which is working fine. But now i want to access a protected URL. Please guide me with a piece of code that how can i access URL with credentials(username/password).
The simple code through which my app loaded the image from URL is given Below
NSURL *url = [NSURL URLWithString: #"http://www.somedirectory.com"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
[Pic setImage:image];
Look For these two callbacks
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
// IF to handle NTLM authentication.
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodNTLM])
return YES;
// Mostly sent by IIS.
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
return YES;
return NO;
}
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
{
if ([[[challenge protectionSpace] authenticationMethod] isEqual:NSURLAuthenticationMethodNTLM])
{
[[challenge sender] useCredential:[NSURLCredential
credentialWithUser:Username
password:password
persistence:NSURLCredentialPersistenceNone]
forAuthenticationChallenge:challenge];
}
else if ([[[challenge protectionSpace] authenticationMethod] isEqual:NSURLAuthenticationMethodServerTrust])
{
[[challenge sender] useCredential:[NSURLCredential
credentialWithUser:Username
password:password
persistence:NSURLCredentialPersistenceNone]
forAuthenticationChallenge:challenge];
}
else
{
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
You can use some third party library like ASIHTTPRequest, which makes it very easy.
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com/top_secret/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:#"username"];
[request setPassword:#"password"];
Or you can use NSURLConnection class, but authentication implementation is a bit tricky.
Related
I have been googling this problem for hours now, and I can't seem to find a solution.
The last tutorial I followed was this tutorial explaining how I could send a JSON request over an untrusted SSL connection (in this case, a self-signed certificate).
In short, the code I have tried so far is this one:
This method checks if the token is valid with my web API:
-(BOOL)linked
{
if([self token] == nil)
{
return NO;
}else
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#?token=%#&object=User&action=check_authorized", SPAtajosApiLink, [self token], nil]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
NSLog(#"%#", req);
[req setHTTPBody: [mandatoryParameters dataUsingEncoding: NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[connection start];
NSDictionary *validity = [NSJSONSerialization
JSONObjectWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil]
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"RESPONSE LINKED %# %#", validity[#"code"], validity[#"message"]);
}
return YES;
}
And I have implemented the NSURLConnectionDelegate methods as follows:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
NSLog(#"API LINK %#", challenge.protectionSpace.host);
if ([challenge.protectionSpace.host isEqualToString:SPAtajosApiLink])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
Yet, my app always crashes with the following message:
2013-10-15 22:48:55.382 Atajos[733:60b] { URL:
https://MY_API_URL/www/?token=657fd6c02b3ba439e69b060f7f7680cc&object=User&action=check_authorized
} 2013-10-15 22:48:58.045 Atajos[733:3b17]
NSURLConnection/CFURLConnection HTTP load failed
(kCFStreamErrorDomainSSL, -9813) 2013-10-15 22:48:58.049
Atajos[733:60b] * Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'data parameter is nil'
* First throw call stack: (0x2ec2de8b 0x38f286c7 0x2ec2ddcd 0x2f5b5d77 0x5df9d 0x62395 0x31433025 0x3141e631 0x313b8be7 0x313b7edd
0x3141dca1 0x3389976d 0x33899357 0x2ebf877f 0x2ebf871b 0x2ebf6ee7
0x2eb61541 0x2eb61323 0x3141cf43 0x314181e5 0x62191 0x39421ab7)
libc++abi.dylib: terminating with uncaught exception of type
NSException
Okay, so NSData, presumably the parameter in NSJSONSerialization is NULL. The question, why?
Bizarrely enough I have a similar code that actually works with a UIWebView interacting with a website over untrusted SSL:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//Need to rebuild base URL. Otherwise I get the parameters which will always fail the check.
NSURL *requestUrl = [request URL];
NSString *basicPathString = [NSString stringWithFormat:#"%#://%#:%#%#", requestUrl.scheme, requestUrl.host, requestUrl.port, requestUrl.path];
NSLog(#"%#", basicPathString);
if([basicPathString isEqualToString:SPAtajosLoginLink])
{
__block NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:request.URL.absoluteURL]
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"Auth token is %#", jsonResponse[#"token"]);
[self dismissViewControllerAnimated:YES completion:^{
if([jsonResponse[#"code"] isEqualToNumber:[NSNumber numberWithInt:200]])
{
[[PDKeychainBindings sharedKeychainBindings] setObject:jsonResponse[#"token"]
forKey:#"com.shortcutpublicity.ios.atajos.userAccessToken"];
}else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"No Se Pudo Autenticar", #"Error 500 title")
message:NSLocalizedString(#"Se ha producido un error interno del servidor (500). Por favor, trata de nuevo más tarde.", #"Error describing error 500")
delegate:nil
cancelButtonTitle:NSLocalizedString(#"Aceptar", #"Accept") otherButtonTitles:nil];
[alertView show];
}
}];
}else {
//--------------THIS IS THE RELEVANT PART------------
BOOL result = _Authenticated;
if (!_Authenticated)
{
_FailedRequest = request;
NSURLConnection *trash = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(trash)
{
NSLog(#"Allocated succesfully.");
}
}
return result;
}
return YES;
}
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURL* baseURL = [NSURL URLWithString:SPatajosAuthLink];
if ([challenge.protectionSpace.host isEqualToString:baseURL.host]) {
NSLog(#"trusting connection to host %#", challenge.protectionSpace.host);
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
} else
NSLog(#"Not trusting connection to host %#", challenge.protectionSpace.host);
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)pResponse {
_Authenticated = YES;
[connection cancel];
[_webView loadRequest:_FailedRequest];
}
I have tried to adapt this code that works with a WebView but I haven't had any luck adapting to use it with a NSURLConnection.
To be honest, I'm not quite sure I know how these workarounds work. I have been stealing and attempting to adapt other people's code to no avail. I have looked at NSURLConnection and NSURLRequest docs and I wasn't able to solve these problems. Please help me out.
We use this category in an #ifedf block for testing... make sure you DO NOT leave this in production:
#ifdef DEBUG
#interface NSURLRequest (IgnoreSSL)
+(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
#end
#implementation NSURLRequest (IgnoreSSL)
+(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host {return YES;}
#end
#endif
try this Delegate method
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
// SecTrustRef trustRef = [[challenge protectionSpace] serverTrust];
// SecTrustEvaluate(trustRef, NULL);
//
// SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, 0);
//
// NSData *certificateData = (__bridge NSData *) SecCertificateCopyData(certRef);
// NSLog(#"Subject: %#", [[NSString alloc] initWithData:certificateData encoding:NSUTF8StringEncoding]);
// [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
SecTrustRef trust = challenge.protectionSpace.serverTrust;
NSURLCredential *cred;
cred = [NSURLCredential credentialForTrust:trust];
[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
}
I am developing an app that plays radio stations. The links for the radio stations are stored on the server and added via a back-end solution.
All information for a radio station such as: name, frequency and of course the stream link are generated by the backend and stored in a XML file. This is my first project so I don't have a clear idea how to download that file, which is stored on a password protected directory.
Do i have to download it via sftp or https?And does anyone have an idea how to perform this task?
Any help would be greatly appreciated.
Thank you in advance.
Granit
You could use NSURLConnection, a good implementation here.To do what you want to do, plain and simple
NSData *responseData = [NSData dataWithContentsOfURL:url];
This happens asynchronously i.e, non - blocking call
dispatch_async(queue, ^{
NSData *responseData = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
// handle your responesData here.
//convert data to nsstring or something then use a parser to parse details.
});
});
Look here for XML Parsing
For basic authentication try this
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 willSendRequestForAuthenticationChallenge:(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 {
...
}
Give your credentials in the willSendRequestForAuthenticationChallenge method or if you want an even better implementation see this, it is an synchronous NSURLConnection subclass imp that also handles authentication.
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.
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.
I was wondering if anyone can help me understand how to add SSL certificate handling to synchronous
connections to a https service.
I know how to do this with asynchronous connections but not synchronous.
NSString *URLpath = #"https://mydomain.com/";
NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
NSMutableURLRequest *myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[myURL release];
[myURLRequest setHTTPMethod:#"POST"];
NSString *httpBodystr = #"setting1=1";
[myURLRequest setHTTPBody:[httpBodystr dataUsingEncoding:NSUTF8StringEncoding]];
NSHTTPURLResponse* myURLResponse;
NSError* myError;
NSData* myDataResult = [NSURLConnection sendSynchronousRequest:myURLRequest returningResponse:&myURLResponse error:&myError];
//I guess I am meant to put some SSL handling code here
Thank you.
Using the static sendSynchronousRequest function is not posible, but i found an alternative.
First of all NSURLConnectionDataDelegate object like this one
FailCertificateDelegate.h
#interface FailCertificateDelegate : NSObject <NSURLConnectionDataDelegate>
#property(atomic,retain)NSCondition *downloaded;
#property(nonatomic,retain)NSData *dataDownloaded;
-(NSData *)getData;
#end
FailCertificateDelegate.m
#import "FailCertificateDelegate.h"
#implementation FailCertificateDelegate
#synthesize dataDownloaded,downloaded;
-(id)init{
self = [super init];
if (self){
dataDownloaded=nil;
downloaded=[[NSCondition alloc] init];
}
return self;
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace: (NSURLProtectionSpace *)protectionSpace {
NSLog(#"canAuthenticateAgainstProtectionSpace:");
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge {
NSLog(#"didReceiveAuthenticationChallenge:");
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[downloaded signal];
[downloaded unlock];
self.hasFinnishLoading = YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[dataDownloaded appendData:data];
[downloaded lock];
}
-(NSData *)getData{
if (!self.hasFinnishLoading){
[downloaded lock];
[downloaded wait];
[downloaded unlock];
}
return dataDownloaded;
}
#end
And for use it
FailCertificateDelegate *fcd=[[FailCertificateDelegate alloc] init];
NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];
NSData *d=[fcd getData];
Now you will have all benefits of have an async use of nsurlconnection and benefits of a simple sync connection, the thread will be blocked until you download all data on the delegate, but you could improve it adding some error control on FailCertificateDelegate class
EDIT: fix for big data. based on Nikolay DS comment. Thanks a lot
I had a similar issue. In my case i had an a-synchronous connection working with ssl as required using the two delegate methods that allowed me to accept any certificate:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
But i was stuck on doing the same in a synchronous manner. I searched the web until i found your post and unfortunately another stackoverflow post where it is hinted that you cannot perform synch calls on NSURLConnection and work with ssl (because of the lack of a delegate to handle the ssl authentication process).
What i ended up doing is getting ASIHTTPRequest and using that. It was painless to do and took me about an hour to set up and its working perfectly. here is how i use it.
+ (NSString *) getSynchronously:(NSDictionary *)parameters {
NSURL *url = [NSURL URLWithString:#"https://localhost:8443/MyApp/";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSString *parameterJSONString = [parameters JSONRepresentation];
[request appendPostString:parameterJSONString];
[request addRequestHeader:#"User-Agent" value:#"MyAgent"];
request.timeOutSeconds = CONNECTION_TIME_OUT_INTERVAL;
[request setValidatesSecureCertificate:NO];
[request startSynchronous];
NSString *responseString = [request responseString];
if (request.error) {
NSLog(#"Server connection failed: %#", [request.error localizedDescription]);
} else {
NSLog(#"Server response: %#", responseString);
}
return responseString;
}
The important part of course is the
[request setValidatesSecureCertificate:NO];
Another alternative for you is to handle the download in another thread with an a-synch connection using the two methods above and block the thread from which you want the synch connection until the request is complete
Im close to finding the solution for this with the code below. This works but often crashes
probably because I am doing something wrong in the way I code this and I don't have a strong understanding of the methods used. But if anyone has any suggestions on how to improve this
than please post.
Just after the line:
NSError* myError;
and just before the line:
NSData* myDataResult = [NSURLConnection sendSynchronousRequest:myURLRequest
returningResponse:&myURLResponse error:&myError];
add:
int failureCount = 0;
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:#"mydomain.com" port:443 protocol:#"https" realm:nil
authenticationMethod:NSURLAuthenticationMethodServerTrust];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:myURL MIMEType:#"text/html"
expectedContentLength:-1 textEncodingName:nil];
NSURLAuthenticationChallenge *challange = [[NSURLAuthenticationChallenge alloc]
initWithProtectionSpace:protectionSpace proposedCredential:[NSURLCredential
credentialForTrust:protectionSpace.serverTrust] previousFailureCount:failureCount
failureResponse:response error:myError sender:nil];