zoukankan      html  css  js  c++  java
  • NSURLConnection 异步加载网络数据

    #import "ViewController.h"


    @interface ViewController ()


    @end


    @implementation ViewController


    - (void)viewDidLoad {

        [super viewDidLoad];

        //[self takeRequestUrlWithString:@"http://127.0.0.1/test.json"];

        //[self takeRequestUrlWithString:@"http://www.baidu.com"];

    }


    -(void)takeRequestUrlWithString:(NSString*)str

    {

        NSURL *url=[NSURL URLWithString:str];

        NSURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];

        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

                if(!connectionError)

                {

                    NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse*)response;

                    if (httpResponse.statusCode==200) {

                        NSError *error=nil;

                        //返回的要么是字典要么是数组

                        id needData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

                        if(error)

                        {

                            NSLog(@"JSON 解析出错:%@",error);

                        }

                        else{

                            NSLog(@"模型转换:数据为:%@",needData);

                        }

                    }

                    else

                    {

                        NSLog(@"服务器出错 ,错误码:%ld",httpResponse.statusCode);

                    }

                    

                }

                else{

                    NSLog(@"连接错误!!!");

                }

        }];

    }

    @end


    @interface RYDataModel : NSObject


    @property(nonatomic,strong)NSNumber *age;

    @property(nonatomic,copy)NSString*name;

    @property(nonatomic,strong)NSDictionary*school;


    +(instancetype)dataWithDict:(NSDictionary*)dict;


    @end


    @implementation RYDataModel


    +(instancetype)dataWithDict:(NSDictionary*)dict

    {

        RYDataModel *model=[RYDataModel new];

        [model setValuesForKeysWithDictionary:dict];

        return model;

    }


    @end

  • 相关阅读:
    BZOJ2219数论之神——BSGS+中国剩余定理+原根与指标+欧拉定理+exgcd
    Luogu 3690 Link Cut Tree
    CF1009F Dominant Indices
    CF600E Lomsat gelral
    bzoj 4303 数列
    CF1114F Please, another Queries on Array?
    CF1114B Yet Another Array Partitioning Task
    bzoj 1858 序列操作
    bzoj 4852 炸弹攻击
    bzoj 3564 信号增幅仪
  • 原文地址:https://www.cnblogs.com/tangranyang/p/4718246.html
Copyright © 2011-2022 走看看