网络相关

控制器销毁后一定要释放NSURLSession
因为它是单例不会被销毁 所以它所开启的任务也都不会被销毁 要自己手动释放

- (void)dealloc{
    [_session invalidateAndCancel];
}

下载图片

UIImage* image = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=440867696,2376631565&fm=173&s=677059CAD826990FFCB4203303008050&w=640&h=427&img.JPEG"]]];

NSURLSession网络请求
注意 如果完成请求后需要更新UI需要获取主线程进行操作 因为网络请求是在子线程进行的

NSURL *url = [NSURL URLWithString:@"http://localhost:3002/test"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSData *postData = [@"name=vijay" dataUsingEncoding:NSUTF8StringEncoding] ;
    //    把字符参数转换成UTF8类型的字符串 form-data的post参数都是xxx=xxx的 浏览器开发者工具显示的xx:xx是为了好看
    request.HTTPBody = postData;
    NSLog(@"%@",[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);
    
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSLog(@"%@",response);
            NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        }
        
    }];
    [task resume];
    

设置NSURLSession代理

//    创建一个自定义配置的session 设置代理和回调要用的线程
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    
//不能用block回调 如果用回调代理方法则不生效
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
   
    [task resume];

下载文件

//
//  ViewController.m
//  GCD
//
//  Created by 杰王 on 2017/12/2.
//  Copyright © 2017年 杰王. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,strong) UIImage* image1;
@property (nonatomic,strong) UIImage* image2;
@property (nonatomic,strong) NSOutputStream* outStream;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self network];
}
-  (void)network{
    NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512260152935&di=3abfd233dfbb7e6f0e2c341012458a05&imgtype=0&src=http%3A%2F%2Fimages.trvl-media.com%2Fhotels%2F4000000%2F3900000%2F3893200%2F3893187%2F3893187_25_y.jpg"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    [[session dataTaskWithURL:url] resume];
    
    
}

#pragma mark - 

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error{
    [_outStream close];
}



- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data{
    [_outStream write:data.bytes maxLength:data.length];
}


/* Sent when a download has been resumed. If a download failed with an
 * error, the -userInfo dictionary of the error will contain an
 * NSURLSessionDownloadTaskResumeData key, whose value is the resume
 * data.
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [caches stringByAppendingPathComponent:@"xxx.jpg"];
    NSLog(@"%@",filePath);
    
    _outStream = [[NSOutputStream alloc ] initToFileAtPath:filePath append:YES];
    [_outStream open];
    
    completionHandler(NSURLSessionResponseAllow);
}

@end

你可能感兴趣的:(网络相关)