使用NSConnection下载数据

来源:互联网 发布:淘宝老顾客拍有权重吗 编辑:程序博客网 时间:2024/05/17 00:00

1. 创建NSConnection对象,设置委托对象

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]];

[NSURLConnection connectionWithRequest:request delegate:self];
复制代码

2. NSURLConnection delegate委托方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (void)connection DidFinishLoading:(NSURLConnection *)connection;
复制代码

3. 实现委托方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// store data
[self.receivedData setLength:0]; //通常在这里先清空接受数据的缓存
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
[self.receivedData appendData:data]; //可多次收到数据,把新数据添加到现有数据最后面
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// 错误处理
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// disconnect
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
NSLog(returnString);
[self urlLoaded:[self urlString] data:self.receivedData];
firstTimeDownloaded = YES;
}
原创粉丝点击