美文网首页
Session会话

Session会话

作者: 小苗晓雪 | 来源:发表于2017-09-08 13:53 被阅读13次
    
    /*
     
     NSURLSession用来替代NSURLConnection。
     
     他相比NSURLConnection 更灵活,更好用。
     
     NSURLSessionUploadTask 继承自 NSURLSessionDataTask 继承自
     NSURLSessionTask
     
     NSURLSessionDownloadTask 继承自 NSURLSessionTask
     
     NSURLSessionDataTask任务默认是挂起状态,使用之前执行resume
     
     */
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [self get];
        [self post];
        [self download];
    }
    
    
    #pragma mark - GET请求
    - (void)get
    {
        //get
        NSString * urlString = @"http://192.168.20.11/login.php";
        
        //创建一个会话类
        NSURLSession * session = [NSURLSession sharedSession];
        
        NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?username=ios&password=123",urlString]];
        
        //Request开启一个任务:
        NSURLSessionDataTask * task1 = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }];
        
        //直接通过Url开启一个任务:
        NSURLSessionDataTask * task2 = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }];
        
        //执行任务:
        [task1 resume];
        [task2 resume];
        
    }
    
    
    #pragma mark - POST请求
    - (void)post
    {
        //一个POST请求:
        NSURL *url = [NSURL URLWithString:@"http://192.168.20.11/login.php"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        //设置请求方法为POST , 默认为GET请求 , 必须使用可变的网络请求类 NSMutableURLRequest 否则 HTTPMethod 是只读属性!
        request.HTTPMethod = @"POST";
        //设置请求体 , get请求和post请求的一个区别就是配置放入请求体里和追加在url后面用?分隔:
        request.HTTPBody = [@"username=ios&password=123" dataUsingEncoding:NSUTF8StringEncoding];
        //获取全局网络会话对象:
        NSURLSession *session = [NSURLSession sharedSession];
        
        //通过Request获取网络数据并执行网络请求:
        [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSLog(@"%@" , [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    
        }] resume];
    
        //通过Url获取网络数据并执行网络请求:
        [[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSLog(@"%@" , [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            
        }] resume];
        
    }
    
    
    #pragma mark - 下载任务请求
    - (void)download
    {
        // stringByAddingPercentEscapesUsingEncoding: 被stringByAddingPercentEncodingWithAllowedCharacters:方法替代:里面传的是一个 集合类 NSCharacterSet;
        // URLQueryAllowedCharacterSet:返回包含URL查询组件中允许的字符的字符集。
        //解决接口中有中文字段的问题:
        NSString * string = [@"http://192.168.20.11/程序员之歌.mp3" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL * url = [NSURL URLWithString:string];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        //Url直接下载:
        [[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            //当前临时文件的地址
            NSLog(@"location - %@",location);
            
            //获取缓存文件目录: suggestedFilename 响应头回传的文件名:
            NSString * cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
            
            //获取缓存文件网络地址:
            NSURL * toUrl = [NSURL fileURLWithPath:cachePath];
            NSFileManager * mgr = [NSFileManager defaultManager];
            
            NSError * error2 = nil;
            //将临时文件移动到缓存文件目录中:
            [mgr moveItemAtURL:location toURL:toUrl error:&error2];
            
        }] resume];
        
        
        //Request下载:
        [[[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            //当前文件所存储的临时地址:
            NSLog(@"%@" , location);
            
            NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
            NSURL *toUrl = [NSURL fileURLWithPath:cachePath];
            NSError *pathError = nil;
            [[NSFileManager defaultManager] moveItemAtURL:location toURL:toUrl error:&pathError];
            
        }] resume];
        
    }
    
    @end
    
    

    愿编程让这个世界更美好

    相关文章

      网友评论

          本文标题:Session会话

          本文链接:https://www.haomeiwen.com/subject/tsigjxtx.html