iosobjective-crestauthenticationprestashop

Restful API call using IOS with authentication


I am working on an application that uses restful API call using Prestashop API. I am new at iOS I coded the same method in Android as:

    InputStream is = null;
try {

 DefaultHttpClient client = new DefaultHttpClient();  
    
    /* adding credentials as it is RESTful call */
    String username = "xyz";
    String password = "";
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),new UsernamePasswordCredentials(username, password));  
// HTTP get request       
HttpGet get = new HttpGet("http://www.example.com/api/");
HttpResponse responseGet;
responseGet = client.execute(get);
is = responseGet.getEntity().getContent();
} catch (ClientProtocolException e) {
    Log.e("HTTP Request","Client Protocol exception" );
} catch (IOException e) {
    Log.e("HTTP Request","IO exception" );
}

It is working perfectly for Android. For iOS I used this coding but I am not getting data from the server.

NSString *userName = @"XYZ";
NSString *password = @"";
//setting the string of the url taking from appliance IP.

NSString *urlString = @"http://www.example.com/api/";

NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:urlString]];

[request setHTTPMethod:@"GET"];

NSString *str1 = [NSString stringWithFormat:@"%@:%@",userName,password];

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

[request addValue:[NSString stringWithFormat:@"Basic %@",str1] forHTTPHeaderField:@"Authorization"];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"str: %@", str);

Please tell me what I am doing wrong and provide any solution.


Solution

  • You can build the URL string this way and it should work :-

    NSString *str1 = [NSString stringWithFormat:@"http://%@:%@@www.example.com/api",userName,password];
    

    No need to use the HTTP header fields I believe