iOS源生HTTP网络请求(get/post)下载任务

来源:互联网 发布:动画合成软件 编辑:程序博客网 时间:2024/06/05 11:45

不经常写,总会忘记,来看看就会想起。

  在info.plist文件操作一下


一.GET请求

NSString *path = @"http://apis.juhe.cn/mobile/get?phone=13301388888&key=4e602dad4a05b4d491ffb82511613158";//如果网址中出现了 中文 需要进行URL编码    path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];    NSURL *url = [NSURL URLWithString:path];    //创建请求    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    //创建网络会话对象    NSURLSession *session = [NSURLSession sharedSession];    //创建数据任务  系统会自动开启一个子线程      NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        //data为服务器返回的数据//        NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];//        NSLog(@"%@",string);        //把服务器返回的json数据 直接转成字典        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];        NSDictionary *resultDic = dic[@"result"];        NSString *province = resultDic[@"province"];        NSString *city = resultDic[@"city"];        NSString *company = resultDic[@"company"];        NSLog(@"%@省 %@市  %@",province,city,company);    }];    //开始任务    [dataTask resume];
二.POST请求

//  POST请求   默认都是Get请求 NSString *path = @"http://v.juhe.cn/joke/randJoke.php";    NSURL *url = [NSURL URLWithString:path];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    //设置请求方式为POST    [request setHTTPMethod:@"POST"];    //请求内容写在 请求体内    [request setHTTPBody:[@"key=8d0bde7167db666ac160191217840b5b&type=pic" dataUsingEncoding:NSUTF8StringEncoding]];    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];        NSLog(@"%@",dic);    }];    [task resume];

三.下载任务

//下载任务 请求 (没有进度)NSString *path = @"http://pic2.desk.chinaz.com/file/10.03.10/5/rrgaos36.jpg";    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];    NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {        //location代表下载后文件的位置 在tmp临时文件        NSLog(@"%@",location);        NSURL *newLocation = [NSURL fileURLWithPath:@"/Users/tarena/Desktop/a.jpg"];        NSFileManager *fm = [NSFileManager defaultManager];        //替换到 新的位置        [fm moveItemAtURL:location toURL:newLocation error:nil];    }];    [task resume];


//下载任务  有进度<NSURLSessionDownloadDelegate>//遵守协议@property (weak, nonatomic) IBOutlet UIProgressView *myPV;//进度属性

NSString *path = @"http://pic2.desk.chinaz.com/file/10.03.10/5/rrgaos36.jpg";    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];    //创建默认会话配置对象    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];//    后面队列的作用  如果给子线程队列则协议方法在子线程中执行 给主线程队列就在主线程中执行    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request];    [task resume];
//实现下载进度协议- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask      didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{    // 每次下载量  已经下载量   总大小    NSLog(@"%lld   %lld  %lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);    self.myPV.progress = totalBytesWritten*1.0/totalBytesExpectedToWrite;}//下载完成会执行  必须实现的协议方法- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location{    NSURL *newLocation = [NSURL fileURLWithPath:@"/Users/tarena/Desktop/bbb.jpg"];    //替换到 新的位置    [[NSFileManager defaultManager]moveItemAtURL:location toURL:newLocation error:nil];    UIImageView *iv = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];    //把路径转成NSData再转成image    iv.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:newLocation.path]];    [self.view addSubview:iv];    }

//可以后台下载任务(需要使用带协议的方法)

//创建默认会话配置对象    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"download"];//只有AppDelegate.m添加了此方法 后台任务 在下载完成时  下载完成的协议方法才会执行  不然要等到回到程序时才执行-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{    NSLog(@"%@",identifier);}




0 0