Search code examples
objective-cioscocoa-touchasihttprequestbasic-authentication

How can I access "http://webservices.ns.nl/ns-api-stations" using ASIHTTPRequest


I am trying to access the XML http://webservices.ns.nl/ns-api-stations using ASIHTTPRequest. But what I am using now doesn't seem to work. It says the host is not reachable. So I assume it is going wrong at the ASIHTTPRequest part?

-(void)fetchStationData {
//Method for the fetching of the data

//First lets check wheater there is an internet connection and if the host is reachable
if(internetActive) {

    //Internet is active

    //Init the parser
    parser = [[RSSParser alloc] init];

    //Set he parser context
    parser.context = context;

    //The array to het the data from 


     NSURL *url = [NSURL URLWithString:@"http://webservices.ns.nl/ns-api-stations"];
     ASIHTTPRequest *requestaccount = [ASIHTTPRequest requestWithURL:url];
     [requestaccount setUsername:@"user"];
     [requestaccount setPassword:@"password"];
    //The XML elements to fetch
    NSArray *elements = [[NSArray alloc] initWithObjects:@"name",nil];
    //The actual fetchin
    [parser fetchStationItemsForUrl:url forElements:elements];

    //Save the context ?
    [context save:nil];

    //Clean up
    [elements release]; 

}else{

    //Internet is down  :( 
    //Offline artikelen inladen

    //Dit uitvoeren op de main que
    dispatch_async(dispatch_get_main_queue(), ^ {

        UIAlertView *Notpermitted = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Er is geen verbinding mogelijk met de Mezz. Offline artikelen zijn ingeladen." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [Notpermitted show];
        [Notpermitted release];

    });

}

}

Solution

  • Use ASIFormDataRequest.

    NSURL *url = [NSURL URLWithString:@"http://webservices.ns.nl/ns-api-stations"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request addPostValue:@"accountname" forKey:@"username"];
    [request addPostValue:@"password" forKey:@"password"];
    
    [request setCompletionBlock:^ {
      // do something when request succeeds and credentials are ok, e.g. redirect user to the home page
    }];
    
    [request setFailedBlock:^ {
      // notify user that request failed
    }];
    
    [request startAsynchronous];