关于 NSURLSession 的上传和下载

本文介绍了如何使用NSURLSession进行文件的上传和下载操作。通过具体的代码示例,详细讲解了NSURLSession的基本使用方法,包括创建NSURLSession实例、配置请求、处理响应及错误等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于 NSURLSession 的上传和下载

在iOS7.0后,苹果公司新推出了一个NSURLSession来代替NSURLConnection。NSURLConnection默认是在 主线程执行的。而NSURLSession是在其他线程上执行的。本篇主要实现了下载和上传,比起NSURLConnection更加简单。线程控制掌握 更加清晰。

pragma mark -下载

  • (IBAction)DownLoad

{

//1.URL 

NSString *urlStr = @"http://she.21cn.com/emotions/mingren/a/2014/0309/15/26645767.shtml";

NSURL *url = [NSURL URLWithString:urlStr];



//2.NSURLRequest

NSURLRequest *request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:5.0];



//3.NSURLSession

NSURLSession *session = [NSURLSessionsharedSession];



NSURLSessionDownloadTask *downLoad = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

    if (error) {

NSLog(@”error = %@”,error.localizedDescription);

    }else{

// location是下载的临时文件目录

NSLog(@”%@”, location);

// 如果要保存文件,需要将文件保存至沙盒

// 1. 根据URL获取到下载的文件名

NSString *fileName = [urlStr lastPathComponent];

// 2. 生成沙盒的路径

NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *path = [docs[0] stringByAppendingPathComponent:fileName];

NSURL *toURL = [NSURL fileURLWithPath:path];

// 3. 将文件从临时文件夹复制到沙盒,在iOS中所有的文件操作都是使用NSFileManager

[[NSFileManager defaultManager] copyItemAtURL:location toURL:toURL error:nil];

// 4. 将图像设置到UIImageView

dispatch_async(dispatch_get_main_queue(), ^{

  UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];

  _imageView.image = image;

});

    }

}];

//4.因为任务默认是挂起状态,需要恢复任务(执行任务)

[downLoad resume];

}
下载

pragma mark -上传

  • (IBAction)upLoad

{

// 0. 判断imageView是否有内容

if (_imageView.image == nil) {

NSLog(@"image view is empty");



return;

}

// 0. 上传之前在界面上添加指示符

UIActivityIndicatorView *indicator = [[UIActivityIndicatorViewalloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

// 设置位置???

CGSize size = _imageView.bounds.size;

indicator.center = CGPointMake(size.width / 2.0, size.height / 2.0);

[self.imageView addSubview:indicator];

[indicator startAnimating];

// 1. URL

NSString *urlStr = @”http://192.168.3.251/uploads/123.jpg“;

NSURL *url = [NSURL URLWithString:urlStr];

// 2. Request -> PUT,request的默认操作是GET

NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:5.0f];

request.HTTPMethod = @”PUT”;

// * 设置网络请求的身份验证! *

// 1> 授权字符串

NSString *authStr = @”admin:123456”;

// 2> BASE64的编码,避免数据在网络上以明文传输

// iOS中,仅对NSData类型的数据提供了BASE64的编码支持

NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];

NSString *encodeStr = [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];

NSString *authValue = [NSString stringWithFormat:@”Basic %@”, encodeStr];

[request setValue:authValue forHTTPHeaderField:@”Authorization”];

// 3. Session

NSURLSession *session = [NSURLSessionsharedSession];

// 4. UploadTask

NSData *imageData = UIImageJPEGRepresentation(_imageView.image, 0.75);

NSURLSessionUploadTask *upload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

// 上传完成后,data参数转换成string就是服务器返回的内容

NSString *str = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"OK -> %@", str);



if (error != nil) {

  NSLog(@"ERROR -> %@", error.localizedDescription);

} else {



}



[NSThreadsleepForTimeInterval:5.0f];



dispatch_async(dispatch_get_main_queue(), ^{

  [indicator stopAnimating];



  [indicator removeFromSuperview];

});

}];

[upload resume];

}
上传

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值