NSURLSession上传图片和其他用法

//上传图片

//iOS 10 上传图片原生代码

-(void)nativeiOSUpImage:(UIImage *)image

{

//此处应设置单例​

    NSURLSessionConfiguration * onConfiguration = [NSURLSessionConfigurationdefaultSessionConfiguration];

    self.session = [NSURLSessionsessionWithConfiguration:onConfiguration delegate:selfdelegateQueue:[NSOperationQueuemainQueue]];

​//开始上传

NSMutableURLRequest * request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:@"http://control.blog.sina.com.cn/blog_rebuild/profile/controllers/points_action.php"]];

[request addValue:@"image/png"forHTTPHeaderField:@"Content-Type"];

[request addValue:@"text/html"forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];

[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];

[request setTimeoutInterval:20];

NSData * imagedata = UIImageJPEGRepresentation(image,1.0);//或NSData *data = UIImagePNGRepresentation(image);//一个是转换JPEG  一个是转换PNG  看需求



NSURLSessionUploadTask * uploadtask = [self.sessionuploadTaskWithRequest:request fromData:imagedata completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[uploadtask resume];

}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{

NSLog(@"%@",error.description);

}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask     *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:    (int64_t)totalBytesSent totalBytesExpectedToSend:    (int64_t)totalBytesExpectedToSend{

}

/////​GET
​// 1.创建一个网络路径

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://blog.sina.com.cn/s/articlelist_3095139511_0_1.html?name=%@&tell=%

",name,tell]];

// 2.创建一个网络请求

NSURLRequest *request =[NSURLRequest requestWithURL:url];

// 3.获得会话对象

NSURLSession *session = [NSURLSession sharedSession];

// 4.根据会话对象,创建一个Task任务:

NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSLog(@"从服务器获取到数据");

             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];

}];

// 5.最后一步,执行任务(resume也是继续执行):

[sessionDataTask resume];

​//POST
​// 1.创建一个网络路径

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://blog.sina.com.cn/s/articlelist_3095139511_0_1.html

"]];

// 2.创建一个网络请求,分别设置请求方法、请求参数

NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];

request.HTTPMethod = @"POST";

NSString *args = [NSString stringWithFormat:@"name=%@&tell=%@",yourname,tell];

request.HTTPBody = UTF-8(args);//此处为宏定义UTF-8编码

// 3.获得会话对象

NSURLSession *session = [NSURLSession sharedSession];

// 4.根据会话对象,创建一个Task任务

NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

NSLog(@"从服务器获取到数据");

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];

}];

//5.最后一步,执行任务,(resume也是继续执行)。

[sessionDataTask resume];

//代理方法

pragma mark -- NSURLSessionDataDelegate// 1.接收到服务器的响应

-  (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {

//【注意:此处需要允许处理服务器的响应,才会继续加载服务器的数据。 如果在接收响应时需要对返回的参数进行处理(如获取响应头信息等),那么这些处理应该放在这个允许操作的前面。】

completionHandler(NSURLSessionResponseAllow);

}

// 2.接收到服务器的数据(此方法在接收数据过程会多次调用)

-  (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {

// 处理每次接收的数据,例如每次拼接到自己创建的数据receiveData

[self.receiveData appendData:data];

}

// 3.任务完成时调用(如果成功,error == nil)

-  (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

if(error == nil){

    

}

else{

    NSLog(@"请求失败:%@",error);

    }

}

//NSURLSessionDownloadTask:文件下载任务
// 1.创建网路路径

  NSURL *url = [NSURL URLWithString:@"http://blog.sina.com.cn/s/articlelist_3095139511_0_1.html

"] ;

// 2.获取会话

NSURLSession *session = [NSURLSession sharedSession];

// 3.根据会话,创建任务

NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

    

 NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

    NSURL *pathUrl = [NSURL fileURLWithPath:path];

    // 剪切文件

    [[NSFileManager defaultManager] moveItemAtURL:location toURL:pathUrl error:nil];

}];

// 4.启动任务

[task resume];

//NSURLSessionDownloadDelegate代理方法
// 1.每次写入调用(会调用多次)

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

// 可在这里通过已写入的长度和总长度算出下载进度

CGFloat progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%f",progress);

}

// 2.下载完成时调用

- (void)URLSession:(NSURLSession *)session

  downloadTask:(NSURLSessionDownloadTask *)downloadTask

didFinishDownloadingToURL:(NSURL *)location {

//  这里的location也是一个临时路径,需要自己移动到需要的路径(caches下面)

NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];

}

// 3.请求成功/失败(如果成功,error为nil)

  - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

if(error == nil){

    

}

else{

    NSLog(@"请求失败:%@",error);

}

}

// 1.创建一个网络路径

  NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?yourname=%@&yourpas=%@&btn=login",yourname,yourpass]];

// 2.创建一个网络请求

NSURLRequest *request =[NSURLRequest requestWithURL:url];

// 3.获得会话对象

NSURLSession *session = [NSURLSession sharedSession];

// 4.根据会话对象,创建一个Task任务:

  NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


    NSLog(@"从服务器获取到数据");


             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];


}];


// 5.最后一步,执行任务(resume也是继续执行):


[sessionDataTask resume];

// 1.创建一个网络路径

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?yourname=%@&yourpas=%@&btn=login",yourname,yourpass]];

// 2.创建一个网络请求

NSURLRequest *request =[NSURLRequest requestWithURL:url];

// 3.获得会话对象

NSURLSession *session = [NSURLSession sharedSession];

// 4.根据会话对象,创建一个Task任务:

NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


    NSLog(@"从服务器获取到数据");


             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];


}];


// 5.最后一步,执行任务(resume也是继续执行):


[sessionDataTask resume];

// 1.创建一个网络路径

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin"]];

// 2.创建一个网络请求,分别设置请求方法、请求参数

NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];


request.HTTPMethod = @"POST";


NSString *args = [NSString stringWithFormat:@"yourname=%@&yourpass=%@&btn=login",yourname,yourpass];


request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];

// 3.获得会话对象

NSURLSession *session = [NSURLSession sharedSession];

// 4.根据会话对象,创建一个Task任务

NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


NSLog(@"从服务器获取到数据");



NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];


}];

//5.最后一步,执行任务,(resume也是继续执行)。

[sessionDataTask resume];

// 1.创建一个网络路径

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin"]];

// 2.创建一个网络请求,分别设置请求方法、请求参数

NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];


request.HTTPMethod = @"POST";


NSString *args = [NSString stringWithFormat:@"yourname=%@&yourpass=%@&btn=login",yourname,yourpass];


request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];

// 3.获得会话对象

NSURLSession *session = [NSURLSession sharedSession];

// 4.根据会话对象,创建一个Task任务

NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


NSLog(@"从服务器获取到数据");



NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];


}];

//5.最后一步,执行任务,(resume也是继续执行)。

[sessionDataTask resume];

你可能感兴趣的:(NSURLSession上传图片和其他用法)