Search code examples
iosobjective-chttpios7arcgis

Accessing the Arcgis secured url using authentication ios


Here I am trying to access the secured URL using the HTTP authentication. But still the data is coming null. code:

{

  NSURL *url = [NSURL URLWithString:@"http://mysecuredurl.com"];

    NSString *userName =@"[email protected]";
    NSString *password =@"12345";

   NSError *myError = nil;

   NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password];
  NSLog(@"loginstring=%@",loginString);

   NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", loginString];
   NSLog(@"auth header =%@",authHeader);

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
                                                          cachePolicy: NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval: 3];
   NSLog(@"request %@",request);

[request addValue:authHeader forHTTPHeaderField:@"Authorization"];
   NSURLResponse *response;
    NSData *data = [NSURLConnection
                    sendSynchronousRequest: request
                    returningResponse: &response
                    error: &myError];
       NSLog(@"data %@",data);

    NSLog(@"response %@",response);

    NSString *result = [[NSString alloc]initWithData:data
                                            encoding:NSUTF8StringEncoding];


    NSLog(@"result = %@",result);

}

Both data and response is null. Please do help me out in this. Is there any changes do I need to do? Thank you.


Solution

  • Your authentication string needs to be base64 encoded. Try -

    NSData *userPasswordData = [[NSString stringWithFormat:@"%@:%@", userName, password] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
    NSString *authHeader= [NSString stringWithFormat:@"Basic %@", base64EncodedCredential]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
                                                              cachePolicy: NSURLRequestReloadIgnoringCacheData
                                                           timeoutInterval: 3];
    
    [request addValue:authHeader forHTTPHeaderField:@"Authorization"];