iOS一个'initWithRequest:delegate:' is deprecated: first deprecated in iOS 9.0 - Use NSURLSessi

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS一个'initWithRequest:delegate:' is deprecated: first deprecated in iOS 9.0 - Use NSURLSessi相关的知识,希望对你有一定的参考价值。

 

技术分享

Warning 如上图所示

源代码片段为

- (void)loadWebRequest:(id)sender {
    NSURL *url=[NSURL URLWithString:@"http://localhost:8080/getAllStudent"];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
    ....
}

此页面为UserInfoViewController()<NSURLConnectionDataDelegate>  遵循了NSURLConnectionDataDelegate协议,并且实现了对应的三个方法

(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

(void)connectionDidFinishLoading:(NSURLConnection *)connection

 

于是谷歌发现http://stackoverflow.com/questions/32647138/nsurlconnection-initwithrequest-is-deprecated

修改刚才的代码片段如下

NSURLSession *session=[NSURLSession sharedSession];
    NSURLSessionTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    ....
    //相关代码逻辑  
}

试着输出了一下data里的数据,发现这个里面的参数data直接就是最终完整的请求数据了!

这样以来就不用UserInfoViewController()<NSURLConnectionDataDelegate>  直接UserInfoViewController()

ios刚入门的小白一枚,希望对大家能有所帮助,共勉

效果图 

 

技术分享

 

 技术分享

 

 

 

附录  

其中的一段网络请求 http://localhost:8080/getAllStudent  是用SpringMVC Tomcat mysql IDEA搭建的本地服务器环境

Xcode代码,IDEA Java代码和MySQL的语句  在此下载https://github.com/hopesala/cnblogs_demo

 
//
//  UserInfoViewController.m
//  iMooc
//
//  Created by 曹城华 on 2017/4/30.
//  Copyright ? 2017年 曹城华. All rights reserved.
//

#import "UserInfoViewController.h"

#define kScreenWidth [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height



// 遵循的协议,协议里面定义了一些方法 NSURLConnectionDataDelegate -->  <NSURLConnectionDataDelegate>
@interface UserInfoViewController ()
{
    //变量
    //NSMutableData *receiveData_;
}

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // viewcontroller  下的--->view
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    UILabel *titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, 20)];
    [titleLabel setText:@"个人信息展示"];
    titleLabel.backgroundColor=[UIColor clearColor];
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.font=[UIFont systemFontOfSize:18];
    
    [self.view addSubview:titleLabel];
    
    
    _userNameView=[[KeyValueView alloc] initWithFrame:CGRectMake(100, 70, kScreenWidth-100*2, 30)];
    _userNameView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_userNameView];
    
    _userSexView=[[KeyValueView alloc] initWithFrame:CGRectMake(100, 70+30, kScreenWidth-100*2, 30)];
    _userSexView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_userSexView];
    
    _birthdayView=[[KeyValueView alloc] initWithFrame:CGRectMake(100, 70+30*2, kScreenWidth-100*2, 30)];
    _birthdayView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_birthdayView];
    
    _emailView=[[KeyValueView alloc] initWithFrame:CGRectMake(100, 70+30*3, kScreenWidth-100*2, 30)];
    _emailView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_emailView];
    
    _phoneView=[[KeyValueView alloc] initWithFrame:CGRectMake(100, 70+30*4, kScreenWidth-100*2, 30)];
    _phoneView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_phoneView];
    
    UIButton *getUserInfoButton=[[UIButton alloc] initWithFrame:CGRectMake(100, 70+30*5, kScreenWidth-100*2, 30)];
    getUserInfoButton.backgroundColor=[UIColor redColor];
    [getUserInfoButton setTitle:@"GetRequest" forState:UIControlStateNormal];
    [getUserInfoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    //loadWebRequest: 冒号表示带有入参
    [getUserInfoButton addTarget:self action:@selector(loadWebRequest:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:getUserInfoButton];
    
    
    
    
    
    // Do any additional setup after loading the view.
}

////网络请求的响应结果
//- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//    NSLog(@"%@",response);
//}
//
////接收网络响应数据, 多次调用
//- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//    if (receiveData_==nil) {
//        receiveData_=[[NSMutableData alloc] init];
//    }
//    [receiveData_ appendData:data];
////    NSLog(@"%@",data);
//}
//
//- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//    NSLog(@"网络请求结束");
//    id obj=[NSJSONSerialization JSONObjectWithData:receiveData_ options:0 error:nil];
//    NSLog(@"%@",obj);
//    if ([obj isKindOfClass:[NSDictionary class]]) {
//        id userInfo=[(NSDictionary *)obj objectForKey:@"items"];
//        NSDictionary *item=[(NSArray *)userInfo objectAtIndex:[userInfo count]-1];
//        
//        NSString *userName=[(NSDictionary *)item objectForKey:@"name"];
//        NSLog(@"%@",userName);
//        
//        NSString *userAge=[(NSDictionary *)item objectForKey:@"age"];
//        NSLog(@"%@",userAge);
//        
//        NSString *userId=[(NSDictionary *)item objectForKey:@"id"];
//        NSLog(@"%@",userId);
//        
//        NSString *userMobole=[(NSDictionary *)item objectForKey:@"mobile"];
//        NSLog(@"%@",userMobole);
//        
//        NSString *userSex=[(NSDictionary *)item objectForKey:@"sex"];
//        if ([userSex isKindOfClass:[NSString class]]) {
//            NSLog(@"aaaaa");
//        }
//        if ([userSex isKindOfClass:[NSNumber class]]) {
//            NSLog(@"bbbbb");
//        }
//        
//        //怎么会变成NSNumber类型了
//        if ([userSex intValue]==1) {
//            [email protected]"男";
//        }
//        if ([userSex isEqual:[NSNumber numberWithInt:0]]) {
//            [email protected]"女";
//        }
//        NSLog(@"%@",userSex);
//
//    }
//}

- (void)loadWebRequest:(id)sender {
    NSURL *url=[NSURL URLWithString:@"http://localhost:8080/getAllStudent"];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
    
    //resume  名词 简历  动词 【继续】
    NSURLSession *session=[NSURLSession sharedSession];
    NSURLSessionTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        id obj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@",obj);
        if ([obj isKindOfClass:[NSDictionary class]]) {
            id userInfo=[(NSDictionary *)obj objectForKey:@"items"];
            NSDictionary *item=[(NSArray *)userInfo objectAtIndex:[userInfo count]-1];
            
            NSString *userName=[(NSDictionary *)item objectForKey:@"name"];
            NSLog(@"%@",userName);
            
            NSString *userAge=[(NSDictionary *)item objectForKey:@"age"];
            NSLog(@"%@",userAge);
            
            NSString *userId=[(NSDictionary *)item objectForKey:@"id"];
            NSLog(@"%@",userId);
            
            NSString *userMobole=[(NSDictionary *)item objectForKey:@"mobile"];
            NSLog(@"%@",userMobole);
            
            NSString *userSex=[(NSDictionary *)item objectForKey:@"sex"];
            if ([userSex isKindOfClass:[NSString class]]) {
                NSLog(@"aaaaa");
            }
            if ([userSex isKindOfClass:[NSNumber class]]) {
                NSLog(@"bbbbb");
            }
            
            //怎么会变成NSNumber类型了
            if ([userSex intValue]==1) {
                userSex=@"";
            }
            if ([userSex isEqual:[NSNumber numberWithInt:0]]) {
                userSex=@"";
            }
            NSLog(@"%@",userSex);
            
        }
    }];
    [dataTask resume];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

 

 

以上是关于iOS一个'initWithRequest:delegate:' is deprecated: first deprecated in iOS 9.0 - Use NSURLSessi的主要内容,如果未能解决你的问题,请参考以下文章

NSURLConnection和Runloop(面试)

允许使用 AFNetworking 的无效证书

Objective c委托自我释放

AFNetworking 3.0 迁移重定向块

ExpressSocket.io开发一个简易的聊天系统

使用 AFNetworking 2.0 下载 PDF 文件