美文网首页
系统的session请求

系统的session请求

作者: LGirl | 来源:发表于2016-07-19 21:35 被阅读29次

    1.GET请求

    self.dataArray = [NSMutableArray array];
    NSURL *url = [NSURL URLWithString:HTTPURL];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
     if (error) {
                NSLog(@"请求失败");
            }else{
                NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                for (NSDictionary *dic in diction) {
                    NEWS *news = [[NEWS alloc] init];
                    [news setValuesForKeysWithDictionary:dic];
                    [self.dataArray addObject:news];
                }
            }
        }];       
    [dataTask resume];
    

    2.POST请求

    - (void)loadData{
        NSString *string = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
        NSURL * url = [NSURL URLWithString:string];
        NSURLSession *session = [NSURLSession sharedSession];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
        request.HTTPMethod = @"POST";
        NSString *dataString = @"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
        NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
        request.HTTPBody = data;
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {
                NSLog(@"请求失败");
            }else {
                NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                for (NSDictionary *dic in diction[@"news"]) {
                    NEWS *news = [[NEWS alloc] init];
                    [news setValuesForKeysWithDictionary:dic];
                    [self.dataArray addObject:news];
                }
                NSLog(@"%@",self.dataArray);
            }
        }];
        [dataTask resume];
    }
    
    
    注意:
    在解析数据的时候,创建news对象的时候,必须要for循环的内部创建,否则,数组中的数据将都一样.
    

    相关文章

      网友评论

          本文标题:系统的session请求

          本文链接:https://www.haomeiwen.com/subject/bgtvjttx.html