iOS NSURLSession UploadTask(上传任务)

1. 简单的上传任务
// 上传文件
- (void)uploadTask {
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/uploads/123.png"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"put";
    [request setValue:[self getAuth:@"admin" pwd:@"1"] forHTTPHeaderField:@"Authorization"];
//    [request setValue:@"Basic YWRtaW46MQ==" forHTTPHeaderField:@"Authorization"];
    // 本地文件
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"head1.png" withExtension:nil];
    [[[NSURLSession sharedSession] uploadTaskWithRequest:request fromFile:fileUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
    }] resume];
}

// 获取授权的字符串
- (NSString *)getAuth:(NSString *)name pwd:(NSString *)pwd {
    // 拼字符串 admin:1
    NSString *tmpStr = [NSString stringWithFormat:@"%@:%@",name,pwd];
    // base64编码
    tmpStr = [self base64Encode:tmpStr];
    return [NSString stringWithFormat:@"Basic %@", tmpStr];
}

// base64编码
- (NSString *)base64Encode:(NSString *)str {
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

2. 监听进度的上传
#import "ViewController.h"

@interface ViewController () <NSURLSessionTaskDelegate>
@property (nonatomic, strong) NSURLSession *session;
@end

@implementation ViewController

// 懒加载
- (NSURLSession *)session {
    if (_session == nil) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:0];
    }
    return _session;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self uploadTask];
}

// 上传文件,监听进度
- (void)uploadTask {
    
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/uploads/123.png"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"put";
    [request setValue:[self getAuth:@"admin" pwd:@"1"] forHTTPHeaderField:@"Authorization"];
    // 本地文件
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"head1.png" withExtension:nil];
    
    [[self.session uploadTaskWithRequest:request fromFile:fileUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"---%@", str);
    }] resume];
}

#pragma mark - 上传进度代理方法
// 上传进度
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
    // 进度 = 已发送的 / 一共需要发送的
    float process = totalBytesSent * 1.0 / totalBytesExpectedToSend;
    NSLog(@"%f", process);
}

// 上传完成
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    NSLog(@"上传完成");
}

// 获取授权的字符串
- (NSString *)getAuth:(NSString *)name pwd:(NSString *)pwd {
    // 拼字符串 admin:1
    NSString *tmpStr = [NSString stringWithFormat:@"%@:%@",name,pwd];
    // base64编码
    tmpStr = [self base64Encode:tmpStr];
    return [NSString stringWithFormat:@"Basic %@", tmpStr];
}

// base64编码
- (NSString *)base64Encode:(NSString *)str {
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

@end
3. NSURLSessionConfiguration配置
3110861-b77499ca0941b7a2.png
NSURLSessionConfigration.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值