1.下载些文本数据把它们转化字符串
NSString *str=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
2.下载一些图片,音视频的数据变为data类型存起来
_data =[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/w%3D310/sign=b6af04fe0b23dd542173a169e108b3df/c9fcc3cec3fdfc03eff99b22d63f8794a5c226a2.jpg"]];
3.同步方法,需要一个request
NSURLRequest *request=[NSURLRequest requestWithURL:url1]
NSData *data2=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
4.异步下载的方法,这就是一条语句
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
Firth
{
Third //这个data参数就是下载数据所处地方
NSString *str3=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}]; Second
它的执行顺序就如上 First Second Third 在下载开始后就一直往后执行,直到等下载完成后再跳回里面来执行 ‘Third‘
5.这个也是异步下载,不过它需要实行协议< NSURLConnectionDataDelegate>中的方法来取值
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self]; ’这个delegate就是协议指针‘
[connection start];
下面几个方法都是可选方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
只有出错才会到这里
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{ //如果是多目标下载 可以通过参数connection 来判断下载来自哪个请求
NSLog(@"Total length: %lld", [response expectedContentLength]); //网页不是正常的文件长度可能出人意料
_totalLength = response.expectedContentLength;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
下载的方法