*NSURLCollection ios9已废弃
一.NSURL对象初始化注意:
1.url里面有空格。
2.url里面不能有汉字。
3.如果里面有汉字需要编码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
二.异步请求方式
1> + sendAsynchronousRequest
// 1.创建地址 NSString *urlStr = @"http://d3.s.hjfile.cn/2012/201202_3/43904b09-24e1-4fdb-8b46-d3dba3323278.mp3"; // 2.创建url urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; // 3.创建NSURLRequest NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 4.开始请求数据 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSLog(@"%@",data); }];
2> + connectionWithRequest delagete 需要遵守代理方法<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
// 第二种 - (void)viewDidLoad { [super viewDidLoad]; [NSURLConnection connectionWithRequest:request delegate:self]; } #pragma mark - NSURLConnection 代理方法 // 收到请求 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // 1.获得文件名称 NSString *fileName = [response suggestedFilename]; // 2.文件大小 long long fileSize = [response expectedContentLength]; // 3.文件类型 NSString *fileType = [response MIMEType]; // 4.状态码(需要转化) // 404,403,500,200 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; NSInteger code = httpResponse.statusCode; // 5.响应头信息 NSDictionary *body = [httpResponse allHeaderFields]; } // 接收到数据 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //1.追加数据 //2.计算进度 //3.刷新界面 //4.写入数据 } // 请求失败 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } // 请求完成 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { //1.刷新界面 //2.数据解析和封装数据模型 }
3> 需要创建对象,手动执行,遵守代理<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
// 第三种 - (void)viewDidLoad { [super viewDidLoad]; // 1.先创建对象 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; // 2.手动执行,代理方法 [connection start]; }
时间: 2024-10-11 22:31:02