1

我正在创建这个应用程序,它与我的网络服务器上的 PHP 脚本通信。

昨晚它工作得很好。但是今天有两个连接没有得到响应。

我已经在浏览器中尝试了 NSURL 链接,它工作正常。还有一个连接工作,但正如我所说的两个连接不起作用?

- (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];
}

连接完成加载:

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

我已经尝试并调试它。

responseTitel 似乎是(空)。

帮助将是apriceated :)

4

1 回答 1

2

didReceiveData 可能会被调用 N (几次) 次。将数据保存到可变数据缓冲区(排队)并在 didFinish 中将其读入字符串

模拟代码:

- (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;
    }
}
于 2012-11-29T13:21:29.673 回答