关于NSURLSession的上传和下载

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

关于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 = [NSURLURLWithString:urlStr];

//2.NSURLRequest

NSURLRequest*request = [NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:5.0];

//3.NSURLSession

NSURLSession*session = [NSURLSessionsharedSession];

NSURLSessionDownloadTask*downLoad = [sessiondownloadTaskWithRequest:requestcompletionHandler:^(NSURL*location,NSURLResponse*response,NSError*error) {

if(error) {

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

}else{

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

NSLog(@"%@", location);

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

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

NSString*fileName = [urlStrlastPathComponent];

// 2.生成沙盒的路径

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

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

NSURL*toURL = [NSURLfileURLWithPath:path];

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

[[NSFileManagerdefaultManager]copyItemAtURL:locationtoURL:toURLerror:nil];

// 4.将图像设置到UIImageView

dispatch_async(dispatch_get_main_queue(), ^{

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

_imageView.image= image;

});

}

}];

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

[downLoadresume];

}

- (IBAction)upLoad

{

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

if(_imageView.image==nil) {

NSLog(@"image view is empty");

return;

}

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

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

//设置位置???

CGSizesize =_imageView.bounds.size;

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

[self.imageViewaddSubview:indicator];

[indicatorstartAnimating];

// 1. URL

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

NSURL*url = [NSURLURLWithString:urlStr];

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

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

request.HTTPMethod=@"PUT";

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

// 1>授权字符串

NSString*authStr =@"admin:123456";

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

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

NSData*authData = [authStrdataUsingEncoding:NSUTF8StringEncoding];

NSString*encodeStr = [authDatabase64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];

NSString*authValue = [NSStringstringWithFormat:@"Basic %@", encodeStr];

[requestsetValue:authValueforHTTPHeaderField:@"Authorization"];

// 3. Session

NSURLSession*session = [NSURLSessionsharedSession];

// 4. UploadTask

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

NSURLSessionUploadTask*upload = [sessionuploadTaskWithRequest:requestfromData:imageDatacompletionHandler:^(NSData*data,NSURLResponse*response,NSError*error) {

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

NSString*str = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];

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

if(error !=nil) {

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

}else{

}

[NSThreadsleepForTimeInterval:5.0f];

dispatch_async(dispatch_get_main_queue(), ^{

[indicatorstopAnimating];

[indicatorremoveFromSuperview];

});

}];

[uploadresume];

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航