1.在实现下载的类中,需要实现协议:NSURLConnectionDataDelegate ,并且要有必要的请求链接;需要定义的属性:
(必须)
NSMutableData *ReceiveData;
NSURLConnection *Connection;
NSURLRequest *Request;
(可选)
NSString *httpUrl;(自定义内容)
NSString *fileName;(自定义内容)
2.在类的实现中:
ReceiveData=[NSMutableData dataWithCapacity:0];
ReceiveData.length=0;
NSURL *url=[NSURL URLWithString:[httpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Request=[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
Connection=[[NSURLConnection alloc]initWithRequest:Request delegate:self];//执行到此时,实现连接后,会自动调用NSURLConnectionDataDelegate中的方法,如下:
3.
//连接响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
fileName = [response suggestedFilename];//若如此做,会自动将文件在网络中的名称自动命名为下载完成后的文件名。
}
//接受数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[ReceiveData appendData:data];//数据累加
NSLog(@"%d",data.length);
}
//接受数据完成后
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *savePath=[NSString stringWithFormat:@"%@/%@.jpg",[paths objectAtIndex:0],fileName];//获得保存路径
NSLog(@"%@",[paths objectAtIndex:0]);
[ReceiveData writeToFile:savePath atomically:YES];//写入文件
}