NSURLsessionTask

  1 #import "ViewController.h"
  2 
  3 @interface ViewController ()
  4 
  5 @property(nonatomic,weak) IBOutlet UIImageView* imageView;
  6 
  7 @end
  8 
  9 
 10 @implementation ViewController
 11 
 12 - (void)viewDidLoad {
 13     [super viewDidLoad];
 14     // Do any additional setup after loading the view, typically from a nib.
 15     self.imageView.backgroundColor = [UIColor grayColor];
 16 }
 17 
 18 -(IBAction)sessionTask:(id)sender{
 19     
 20     NSString* urlStr1 = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=3";
 21     NSString* urlStr2 = @"http://photo.candou.com/i/114/826ea823e8ffe792a6fda9e126f6c404";
 22     
 23     //进行dataTask 的任务
 24 //    [self downloadWithDataTask:urlStr1];
 25     
 26     //进行downloadTask 的任务
 27     [self downloadWithDownloadTask:urlStr2];
 28 
 29     //上传UploadTask任务
 30 //    [self uploadWithUploadTask:urlStr1];
 31     
 32 }
 33 /**
 34      根据职能不同Task有三种子类:
 35      NSURLSessionUploadTask:上传用的Task,传完以后不会再下载返回结果;
 36      NSURLSessionDownloadTask:下载用的Task,下载内容到硬盘上;
 37      NSURLSessionDataTask:可以上传内容,上传完成后再进行下载,存储为NSData格式。
 38  */
 39 #pragma mark -三种Task任务的基本演示-
 40 
 41 //可以上传内容,上传完成后再进行下载,存储为NSData格式
 42 -(void)downloadWithDataTask:(NSString*)urlStr{
 43     
 44     NSURL *url = [NSURL URLWithString:urlStr];
 45     
 46     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 47     //使用一个系统默认的会话(缓存策略、cookie、鉴权等使用默认)
 48     NSURLSession *session = [NSURLSession sharedSession];
 49     //接受数据类的任务
 50     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
 51         NSLog(@"data:%@",data);
 52         NSLog(@"response:%@",response);
 53         NSLog(@"error:%@",error);
 54     }];
 55     //执行任务
 56     [dataTask resume];
 57 }
 58 
 59 //下载用的Task,下载内容到硬盘上
 60 -(void)downloadWithDownloadTask:(NSString*)urlStr{
 61     
 62     NSURL *url = [NSURL URLWithString:urlStr];
 63     
 64 //    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
 65     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 66     //使用一个系统默认的会话(缓存策略、cookie、鉴权等使用默认)
 67     NSURLSession *session = [NSURLSession sharedSession];
 68     //下载类的任务
 69     NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
 70         
 71         NSLog(@"location:%@",location);
 72         NSLog(@"response:%@",response);
 73         NSLog(@"error:%@",error);
 74         
 75         NSData *data = [NSData dataWithContentsOfURL:location];
 76 //        self.imageView.image = [UIImage imageWithData:data];
 77         
 78         //获取Document目录
 79         NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)  firstObject];
 80         //将字符串路径转换成URL
 81         NSURL *documentUrl = [NSURL fileURLWithPath:documentPath];
 82         //更改路径,把最后的文件追加到自己设定的路径后,组成新的路径
 83         NSURL *newUrl = [documentUrl URLByAppendingPathComponent:[location lastPathComponent]];
 84         
 85         NSLog(@"newUrl:%@",newUrl);
 86         //将返给路径的文件夹移动到新的路径下
 87         [[NSFileManager defaultManager] moveItemAtURL:location toURL:newUrl error:nil];
 88     }];
 89     //执行任务
 90     [downloadTask resume];
 91 }
 92 
 93 //上传用的Task,传完以后不会再下载返回结果
 94 -(void)uploadWithUploadTask:(NSString*)urlStr{
 95     
 96     NSURL *url = [NSURL URLWithString:urlStr];
 97     
 98     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 99     NSData *data = nil;
100     
101     //使用一个系统默认的会话(缓存策略、cookie、鉴权等使用默认)
102     NSURLSession *session = [NSURLSession sharedSession];
103     //上传类的任务
104     NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
105         NSLog(@"data%@",data);
106         NSLog(@"response%@",response);
107         NSLog(@"error%@",error);
108     }];
109     //执行任务
110     [uploadTask resume];
111 }
112 
113 
114 
115 - (void)didReceiveMemoryWarning {
116     [super didReceiveMemoryWarning];
117     // Dispose of any resources that can be recreated.
118 }
119 
120 @end
View Code

 

转载于:https://www.cnblogs.com/sdutmyj/p/4774109.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 iOS 13 之前,可以使用 `CFStream` 和 `CFNetwork` 库来创建 TCP 长连接。以下是一个简单的示例: ```objc CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)@"example.com", 80, &readStream, &writeStream); CFReadStreamOpen(readStream); CFWriteStreamOpen(writeStream); // 写入数据 NSString *requestStr = @"GET / HTTP/1.0\r\n\r\n"; NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding]; CFIndex bytesWritten = CFWriteStreamWrite(writeStream, [requestData bytes], [requestData length]); NSLog(@"%ld bytes written", bytesWritten); // 读取数据 UInt8 buffer[1024]; CFIndex bytesRead = CFReadStreamRead(readStream, buffer, sizeof(buffer)); NSLog(@"%ld bytes read", bytesRead); CFReadStreamClose(readStream); CFWriteStreamClose(writeStream); CFRelease(readStream); CFRelease(writeStream); ``` 在 iOS 13 之后,`CFNetwork` 库被宣布废弃,推荐使用 `NSURLSession` 或 `Network.framework` 来创建网络连接。以下是使用 `NSURLSession` 创建 TCP 长连接的示例: ```objc NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; config.allowsCellularAccess = YES; config.timeoutIntervalForResource = 60.0; NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; NSURL *url = [NSURL URLWithString:@"http://example.com"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"GET"; NSURLSessionDataTask *task = [session dataTaskWithRequest:request]; [task resume]; ``` 在 `NSURLSessionDelegate` 协议中实现以下方法以处理响应: ```objc - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"Received %ld bytes", [data length]); } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error) { NSLog(@"Request failed with error: %@", error); } else { NSLog(@"Request finished successfully"); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值