查询手机号码归属地 json 解析数据

           首先创建控件   然后导入MB 文件夹 MBProgressHUD

             导入头文件#import "MBProgressHUD/MBProgressHUD.h"  

              创建类别文件 NSstring+regular

               .h中填写方法:

//判断是否是一个正确的手机号

-(BOOL)isCorrectPhoneNumber;

                 .m 中实现方法:

//判断是否是一个正确的手机号

-(BOOL)isCorrectPhoneNumber{

    //如果不是11位 返回 NO

    if(self.length!=11) {

        returnNO;

    }

    //如果够11位, 如果以10 11 开头返回 YES

    if ([self hasPrefix:@"13"] || [self hasPrefix:@"14"] || [self hasPrefix:@"15"] || [self hasPrefix:@"16"] || [self hasPrefix:@"17"] || [self hasPrefix:@"18"] || [self hasPrefix:@"19"]) {

        returnYES;

    }


    //剩下的都判定错误

    return NO;

}

   导入头文件#import "NSString+Regular.h"


                      控件拖入:

@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

- (IBAction)search:(id)sender;

@property (weak, nonatomic) IBOutlet UITextView *textVi;

//显示提示框

-(void)showMBAlertWithMassage:(NSString*)msg{

    MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];


    hud.mode = MBProgressHUDModeText;


    hud.removeFromSuperViewOnHide = YES;


    hud.labelText= msg;


    [self.viewaddSubview:hud];


    [hudshow:YES];


    [hudhide:YES afterDelay:2.0];

}

- (IBAction)search:(id)sender {


    if(self.phoneTF.text.length==0){


        [self showMBAlertWithMassage:@"手机号不可为空"];

        return;

    }


    //做手机号的判断

    if ([self.phoneTF.text isCorrectPhoneNumber] == NO) {


        [self showMBAlertWithMassage:@"请输入正确的手机号"];


        return;

    }



    //使用 GET 请求网络数据

   [self requestNetDataByGET];

    //使用 POST 请求网络数据

    [self requestNetDataByPOST];

}

//使用 GET 请求网络数据

-(void)requestNetDataByGET{


    //显示等待显示器


    MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];


    hud.removeFromSuperViewOnHide = YES;


    [self.viewaddSubview:hud];


    [hudshow:YES];




    // (1)封装网址字符串 并把参数连接到字符串上


    NSString *URL = [NSString stringWithFormat:@"http://apis.juhe.cn/mobile/get?phone=%@&key=%@",self.phoneTF.text,@"74a36daf6c9af664e4ef26bbeaa9085c"];


    // (2) 将网址字符串封装为地址对象


    NSURL*url = [NSURLURLWithString:URL];


    // (3) 做一个请求对象 设置缓存策略和超市时长


    NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5.0];


    // (4)

    [self usesessionRequestData:req hud:hud];



}

   POST方法

-(void)requestNetDataByPOST{


    //显示等待显示器


    MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];


    hud.removeFromSuperViewOnHide = YES;


    [self.viewaddSubview:hud];


    [hudshow:YES];



    //将网址字符串封装为网址对象


    NSURL *url = [NSURL URLWithString:@"http://apis.juhe.cn/mobile/get"];


    //做一个请求对象


    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5.0];


    //设置请求方式魏 post


    [reqsetHTTPMethod:@"POST"];


    //将参数坐成一个字符串

    NSString *paramStr = [NSString stringWithFormat:@"phone=%@&key=%@",self.phoneTF.text,@"74a36daf6c9af664e4ef26bbeaa9085c"];


    //将参数字符串转换为二进制对象


    NSData *parmeData = [paramStr dataUsingEncoding:NSUTF8StringEncoding];


    //将参数二进制数据放在请求体中


    [reqsetHTTPBody:parmeData];


    [self usesessionRequestData:req hud:hud];




}

//请求网络数据

-(void)usesessionRequestData:(NSURLRequest*)req hud:(MBProgressHUD*)hud{


    // (3)请求网络数据

    NSURLSession *session = [NSURLSession sharedSession];


    //(5)请求网络数据任务

    NSURLSessionDataTask*task = [sessiondataTaskWithRequest:reqcompletionHandler:^(NSData*_Nullabledata,NSURLResponse*_Nullableresponse,NSError*_Nullableerror) {

        //停掉等待指示器


        dispatch_async(dispatch_get_main_queue(), ^{

            [hudhide:YES];

        });


        //如果发生服务器错误

        if(error !=nil) {

            //回到 UI 主线程提示


            dispatch_async(dispatch_get_main_queue(), ^{


                [self showMBAlertWithMassage:@"服务器错误"];


            });


            return;

        }


        //解析 JSON 数据


        NSError*jsonError =nil;


        id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];


        //如果json解析错误 给出提示 并结束调用


        if(jsonError !=nil) {

            dispatch_async(dispatch_get_main_queue(), ^{

                [self showMBAlertWithMassage:@"网络数据错误"];

            });

            return;

        }


        //json 解析正确 得到resultcode字段的值不是200 发生错误 给客户提示


        if([[jsonDataobjectForKey:@"resultcode"]intValue] !=200) {


            //获取reason

            NSString*reason = jsonData[@"reason"];


            dispatch_async(dispatch_get_main_queue(), ^{

                [selfshowMBAlertWithMassage:reason];

            });


            return;


        }

        //没有错误 提取归属地信息

        NSDictionary*resultDic = jsonData[@"result"];

        NSString*province = resultDic[@"province"];

        NSString*city = resultDic[@"city"];

        NSString*areacode = resultDic[@"areacode"];

        NSString*zip = resultDic[@"zip"];

        NSString*company = resultDic[@"company"];

        NSString*card = resultDic[@"card"];

        //用一个字符串拼接到一块

        NSString*resultStr = [NSStringstringWithFormat:@"省:%@\n\

                               市:%@\n\

                               区号:%@\n\

                               邮编:%@\n\

                               公司:%@\n\

                               类型:%@",province,city,areacode,zip,company,card];

        dispatch_async(dispatch_get_main_queue(), ^{

            self.textVi.text= resultStr;

        });

    }];

    [taskresume];

}

最后 :info.plist 中开启网络

App Transport Security Settings

Allow Arbitrary Loads   后面跟 YES.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容