iOS一個'initWithRequest:delegate:' is deprecated: first deprecated in iOS 9.0 - Use NSURLSession (see NSURLSession.h) Warning引發的思考


 

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) {
//            userSex=@"男";
//        }
//        if ([userSex isEqual:[NSNumber numberWithInt:0]]) {
//            userSex=@"女";
//        }
//        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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM