Mads Odgaard
Mads Odgaard

Reputation: 33

Objective C NSURLConnection dosen't get response data

I am creating this application, it communicates with a PHP script on my web-server.

Last night it was working perfectly. But today two of the connections does not get response.

I've tried the NSURL link in my browser, it works fine. Also one of the connections work, but as i said two connections does not work?

- (void) getVitsTitelByID:(int)id {

NSString *url = [NSString stringWithFormat:@"http://webserver.com   /ivitserdk.php?function=gettitelbyid&id=%d", id];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0];
connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

connectionDidReciveData:

if(connection == connectionTitelByID){
    responseTitel = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

connectionDidFinishLoading:

if(connection == connectionTitelByID){
    titelLabel.text = responseTitel;
}

I've tried and debugging it.

responseTitel seems to be (null).

Help would be apriceated :)

Upvotes: 1

Views: 2800

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50089

didReceiveData may be called N (several) times. save the data to a mutably data buffer (queue it up) and in didFinish read it into a string

mock code:

- (void) getVitsTitelByID:(int)identifier {
    NSString *url = [NSString stringWithFormat:@"http://webserver.com/ivitserdk.php?function=gettitelbyid&id=%d", identifier];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0];
    connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    dataForConnectionTitelByID = [NSMutableData data];
    [connectionTitelByID start];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if(!data.length) return;

    if(connection == connectionTitelByID)
        [dataForConnectionTitelByID appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if(connection == connectionTitelByID) {
        id str = [[NSString alloc] initWithData:dataForConnectionTitelByID encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        dataForConnectionTitelByID = nil;
        connectionTitelByID = nil;
    }
}

Upvotes: 2

Related Questions