UI之网路请求(进度条小知识)

本文介绍如何使用iOS的NSURLSession进行异步下载,并展示如何处理下载进度与响应,包括图片和MP3文件的下载过程及进度条更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDataDelegate,NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageV;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;


@property(nonatomic,strong)NSMutableData *imageData;
//进度条
//@property(nonatomic,strong)UIProgressView *progress;
@property(nonatomic,strong)UIView *view1;
@property(nonatomic,strong)UIView *view2;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /*
      url全称是 Uniform Resource Locator(统一资源占位符)
     通过一个URL,能找到互联网上唯一的一个资源
     URL就是资源的地址、weizhi,互联网上的每个资源都有唯一的一个URL
     URL的基本格式=协议://主机地址/路径
     例如:HTTP://www.sina.com.cn/szzr/
     协议:不同的协议,代表着不同的资源查找方式,资源传输方式
     主机地址:存放资源的主机的IP地址(域名)
     路径:资源在主机中的位置
     */
//    [self downLoadMp3EithBefore7];
    [self downLoadMp3WithAffer7];
    [self downLoadDataWithProgress];


    //用uiview设置一个大的进度条
    _view1 = [[UIView alloc] initWithFrame:CGRectMake(42, 600, 266, 20)];
    _view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    _view1.backgroundColor = [UIColor grayColor];
    _view2.backgroundColor = [UIColor greenColor];
    [self.view addSubview:_view1];
    [self.view addSubview:_view2];

}
#pragma -mark Xcode之前的写法
-(void)downLoadMp3EithBefore7
{
    //1.创建url
    NSString *str = @"http://60.190.216.110:8880/accompany_onlinePlay_130115exut/memberaccompany/songfolder/2009/11/13/608c3024c9f941ce8bf64f6ed4051c34.mp3";
    NSURL *url = [NSURL URLWithString:str];

    //2.通过url创建网络请求(可变请求)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:600];
    //3发送请求(异步请求)
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//        NSString *docpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//        NSLog(@"%@",docpath);
//        NSString *mp3path = [docpath stringByAppendingPathComponent:@"说谎.MP3"];
//        [data writeToFile:mp3path atomically:YES];
//        NSLog(@"下载完成");
//        
//    }];

    //同步请求 程序会在运行到同步请求行代码卡住 知道下载结束
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSLog(@"%@",data);



}

#pragma mark -Xcode之后的用法
-(void)downLoadMp3WithAffer7
{
//    //get请求
//    NSString *str = @"http://60.190.216.110:8880/accompany_onlinePlay_130115exut/memberaccompany/songfolder/2009/11/13/608c3024c9f941ce8bf64f6ed4051c34.mp3";
//    NSURL *url = [NSURL URLWithString:str];
//    //2.创建会话
//    NSURLSession *session = [NSURLSession sharedSession];
//    //如果需要发送post请求就创建request 因为request可以设置请求的方式 默认的请求是get方式
//    //3.创建任务
//    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//       
//        //更新UI的操作 必须在主线程
//        //记住一点 异步请求本质是多线程
//        //主线程中禁止做耗时操作(一个APP只有一个主线程)
//        //回到主线程(GCD)
//        dispatch_async(dispatch_get_main_queue(), ^{
//            NSString *docpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//            NSString *mp3path = [docpath stringByAppendingPathComponent:@"说谎.MP3"];
//            [data writeToFile:mp3path atomically:YES];
//            NSLog(@"下载完成");
//            
//        });
//        
//    }];
//    //4.执行任务(默认是挂起状态)
//    [task resume];



    //发送post请求
    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //添加请求体(请求体式一个NSData 我们用post的目的是想保密一部分数据,我们将这部分数据转化成NSData类型 放入请求体中)
    NSString *body = @"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    //会话
    NSURLSession *session = [NSURLSession sharedSession];
    //任务
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       //data转字符串
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",string);

    }];
    //启动
    [task resume];

    //缓慢显示图片
    NSString *str1 = @"http://www.xiaoxiongbizhi.com/wallpapers/__85/1/9/19r0an0jm.jpg";
    NSURL *url1 = [NSURL URLWithString:str1];
    NSURLSession *session1 = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task1 = [session1 dataTaskWithURL:url1];
    [task1 resume];

}

#pragma mark -异步请求的代理方法
//收到响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //允许处理
    completionHandler(NSURLSessionResponseAllow);
    _imageData = [NSMutableData data];
}
//收到数据
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [_imageData appendData:data];
    _imageV.image = [UIImage imageWithData:_imageData];

}
//失败
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"%@",error);
}

//进度条下载MP3
-(void)downLoadDataWithProgress
{
    NSString *str = @"http://60.190.216.110:8880/accompany_onlinePlay_130115exut/memberaccompany/songfolder/2009/11/13/608c3024c9f941ce8bf64f6ed4051c34.mp3";
    NSURL *url = [NSURL URLWithString:str];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
    [task resume];

}

//获取资源大小的代理方法
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"%lld",totalBytesWritten);
    NSLog(@"%lld",totalBytesExpectedToWrite);
    //走得语句
    _progress.progress = 1.0*totalBytesWritten/totalBytesExpectedToWrite;
    //重新定义坐标
    _view2.frame = CGRectMake(42, 600, 266.0*totalBytesWritten/totalBytesExpectedToWrite, 20);
}

//下载完成
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"下载完成");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值