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配置

NSURLSessionConfigration.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容