美文网首页
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

愿编程让这个世界更美好

相关文章

  • PHP Session

    PHP session 变量用于存储关于用户会话(session)的信息,或者更改用户会话(session)的设置...

  • session、token与jwt

    session与cookie 什么是session session翻译过来是会话,但在WEB领域常常是指会话数据:...

  • ubuntu tmux 快捷键

    session 新建tmux会话tmux new -s [name of session] 在已有tmux会话基础...

  • Session的简单了解 -- PHP 学习 (十六)

    (a) session_start — 启动新会话或者重用现有会话 session_start ([ array ...

  • JavaWeb之Cookie和Session

    七、Cookie和Session 目录:会话、Cookie、Session(重点) 1.会话 会话:用户打开一个浏...

  • php session的基础知识

    什么是session? session变量用于存储有关用户会话的信息,或更改用户会话的设置。Session 变量保...

  • Session对象(1)

    session作用:主要用于跟踪会话 session作用域:会话期间 使用session对象来显示跟踪员工的登录账...

  • Zookeeper会话管理

    Zookeeper会话管理 一,会话实体Session类 Session是一个接口,定义在SessionTrack...

  • Redis的5个常见使用场景

    会话缓存(Session Cache) 最常用的一种使用Redis的情景是会话缓存(session cache)。...

  • Java Web之会话追踪

    会话追踪: Cookie: Session:

网友评论

      本文标题:Session会话

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