iOS NSURLSession网络请求(get/post/下载)

NSURLConnection在iOS 9.0以后就废弃了
DEPRECATED  deprecated废弃的意思
NSURLSession  已经代替了NSURLConnection  功能上差不多.NSURLSession使用起来更方便,支持下载和上传文件,断点续传等使用起来很方便
苹果将每次请求都定义为一个任务
NSURLSessionDataTask  是请求普通网络数据的任务类
NSURLSessionUploadTask  上传任务类(需要和服务器配合使用)
NSURLSessionDownloadTask  下载任务类

我使用storyBoard拖了3个按钮,一个imageView,如图:
这里写图片描述

关联控件

@interface ViewController : UIViewController

- (IBAction)getBtn:(UIButton *)sender;  //get请求

- (IBAction)postBtn:(UIButton *)sender;  //post请求

- (IBAction)downImage:(UIButton *)sender;  //下载图片

@property (strong, nonatomic) IBOutlet UIImageView *myImageView;  //imageView

@end

声明属性

//下载需要签协议
@interface ViewController ()<NSURLSessionDownloadDelegate>

@property (nonatomic, strong)NSURLSessionDataTask *tast;
@property (nonatomic, strong)NSURLSessionDataTask *posttast;
@property (nonatomic, strong)NSURLSessionDownloadTask *downTast;

@end

get请求

- (IBAction)getBtn:(UIButton *)sender {

   //url字符串地址
    NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
    //中文编码
    NSString *strEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //废弃了
    //转码--->中文,(由于不能转特殊字符)
//    NSString *urlEncode2 = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    //生成系统能够识别的NSURL对象
    NSURL *url = [NSURL URLWithString:strEncode];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //创建网络连接对象
    NSURLSession *session = [NSURLSession sharedSession];
    //创建请求普通数据网络任务tast
    self.tast = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //json解析data数据
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"result == %@", result);
    }];
    //开始请求任务
    [self.tast resume];
}

post请求

- (IBAction)postBtn:(UIButton *)sender {

    //post地址
    NSString *urlStr = @"http://api.hoto.cn/index.php?appid=4&appkey=573bbd2fbd1a6bac082ff4727d952ba3&appsign=cee6710ae48a3945b398702d8702510a&channel=appstore&deviceid=0f607264fc6318a92b9e13c65db7cd3c%7C552EE383-0FAD-4555-9979-AC38A01C5D6D%7C9C579DCC-7C8F-4E53-AEB6-54527C473309&format=json&loguid=&method=Recipe.getFindRecipe&nonce=1443856978&sessionid=1443856790&signmethod=md5&timestamp=1443856978&uuid=02288be08f4b871a69565746255b0de9&v=2&vc=40&vn=v5.1.0";
    NSString *strEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:strEncode];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //设置请求对象的请求方式为post,默认是get请求
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = @"cacheKey=Recipe.getFindRecipe&sign=&uid=&uuid=02288be08f4b871a69565746255b0de9";
    //将body体字符串转成data数据
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    //设置为请求的body体
    [request setHTTPBody:bodyData];

    //创建一个专门配置session的类,是系统对session对象的标准配置
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    //另一种初始化方法
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];

    self.posttast = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"post result = %@", result);
    }];
    [self.posttast resume];

}

下载图片

- (IBAction)downImage:(UIButton *)sender {

    NSString *urlStr = @"http://avatar0.hoto.cn/36/76/3962422_185.jpg?v=11";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionConfiguration *sessionCon = [NSURLSessionConfiguration defaultSessionConfiguration];
    //参数3:创建一个主线程列队
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionCon delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    // NSURLSessionDataDelegate 协议名

    //创建下载任务
    self.downTast = [session downloadTaskWithRequest:request];
    //执行下载任务
    [self.downTast resume];

}
//下载完成时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{

    NSLog(@"下载存放的临时路径 = %@", location.path);
    //获取app本地缓存路径
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSString*imagePath = [filePath stringByAppendingPathComponent:@"image.png"];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // [NSFileManager defaultManager]是系统单例

    //将下载文件移动到caches文件下
    [fileManager moveItemAtPath:location.path toPath:imagePath error:nil];
    NSLog(@"filePath = %@", filePath);

    //将下载的图片显示到手机上
    self.myImageView.image = [UIImage imageWithContentsOfFile:imagePath];

}

下载视频也是可以的,我直接把下载图片按钮的点击事件,改成了下载视频,并又拖了进度条和2个按钮,如图:
这里写图片描述

关联控件

@property (retain, nonatomic) IBOutlet UIProgressView *progress;

- (IBAction)stopBtn:(UIButton *)sender;  //暂停按钮

- (IBAction)resume:(UIButton *)sender;  //继续按钮
- (IBAction)downImage:(UIButton *)sender {

    NSString *urlStr = @"http://hc25.aipai.com/user/656/20448656/6167672/card/25033081/card.mp4?l=a";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionConfiguration *sessionCon = [NSURLSessionConfiguration defaultSessionConfiguration];
    //参数3:创建一个主线程列队
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionCon delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    // NSURLSessionDataDelegate 协议名

    //创建下载任务
    self.downTast = [session downloadTaskWithRequest:request];
    //执行下载任务
    [self.downTast resume];

}
//下载完成时调用
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    NSLog(@"下载存放的临时路径 = %@", location.path);
    //获取app本地缓存路径
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSString*imagePath = [filePath stringByAppendingPathComponent:@"image.mp4"];

    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // [NSFileManager defaultManager]是系统单例

    //将下载文件移动到caches文件下
    [fileManager moveItemAtPath:location.path toPath:imagePath error:nil];
    //进到文件夹里就能看见下载的视频了
    NSLog(@"filePath = %@", filePath);
}
//每下载完一部分就会触发该方法
//参数1:bytesWritten:下载速度
//参数2:totalBytesWritten:已经下载多少
//参数3:totalBytesExpectedToWrite:文件总大小
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

    NSLog(@"速度:%lldkb/s 已经下载:%lldkb 文件总大小:%lldkb", bytesWritten/1024, totalBytesWritten/1024, totalBytesExpectedToWrite/1024);

    //下载的视频与进度条关联
    double Progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    self.progress.progress = Progress;
}


- (IBAction)stopBtn:(UIButton *)sender {
    //暂停下载
    [self.downTast suspend];
}

- (IBAction)resume:(UIButton *)sender {
    //继续下载
    [self.downTast resume];
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值