【问题标题】:How to populate JSON data in UITableView using NSUrlConnection? [duplicate]如何使用 NSUrlConnection 在 UITableView 中填充 JSON 数据? [复制]
【发布时间】:2014-09-15 15:01:47
【问题描述】:

我正在构建一篇文章阅读应用程序。我正在使用 UITableView 中的 NSData 解析 JSON 数据。

我遇到了一个问题,即网速慢(2g 或 3g)无法加载数据意味着 UI 是空的。
我想实现 NSUrlConnection 但我是 iOS 开发新手,无法在我的代码中实现 NSUrlConnection。

这是我的代码:

      - (void)viewDidLoad
       {
            [super viewDidLoad];
            BOOL myBool = [self isNetworkAvailable];
            if (myBool)
            {
              @try {
                // for table cell seperator line color
               self.tableView.separatorColor = [UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:1.0];

           UIBarButtonItem *backbutton1 = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
           [[self navigationItem] setBackBarButtonItem:backbutton1];
           _Title1 = [[NSMutableArray alloc] init];
           _Author1 = [[NSMutableArray alloc] init];
           _Images1 = [[NSMutableArray alloc] init];
           _Details1 = [[NSMutableArray alloc] init];
           _link1 = [[NSMutableArray alloc] init];
           _Date1 = [[NSMutableArray alloc] init];

           NSData* data = [NSData dataWithContentsOfURL:ysURL];
           NSArray *ys_avatars = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
           if(ys_avatars){
           for (int j=0;j<ys_avatars.count;j++)
              {
               if( ys_avatars[j][@"title"]==[NSNull null] ){
               [_Title1 addObject: @""];
             }
            else{
              [_Title1 addObject:ys_avatars[j][@"title"]];
                }
              if( ys_avatars[j][@"author"]==[NSNull null] ){
              [_Author1 addObject: @""];
                }
              [_Author1 addObject: ys_avatars[j][@"author"]];
              if( ys_avatars[j][@"featured_img"]==[NSNull null] ){
              [_Images1 addObject: @""];
                }
                else{
                    [_Images1 addObject: ys_avatars[j][@"featured_img"]];
             }
                if( ys_avatars[j][@"content"]==[NSNull null] ){
                [_Details1 addObject: @""];
               }else{
              [_Details1 addObject:ys_avatars[j][@"content"]];
                }
                if( ys_avatars[j][@"permalink"]==[NSNull null] ){
              [_link1 addObject: @""];
           }
                else{
                    [_link1 addObject:ys_avatars[j][@"permalink"]];
                }
                if( ys_avatars[j][@"date"]==[NSNull null] ){
               [_Date1 addObject: @""];
              }
                else{
               NSString *newStr=[ys_avatars[j][@"date"] substringToIndex:[ys_avatars[j][@"date"] length]-3];
              [_Date1 addObject:newStr];
                }
            }
         }
        else
        {
            NSLog(@"asd");

           }
         }
        @catch (NSException *exception) {
              }

          }
        }

        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
          {
            static NSString *Cellidentifier1 = @"ysTableViewCell";
            ysTableViewCell *cell1 = [tableView   dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];
            long row = [indexPath row];
            cell1.TitleLabel1.text = _Title1[row];
            cell1.AuthorLabel1.text = _Author1[row];
             NSString *StoryUrl = [_Images1[indexPath.row]      stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
             if(StoryUrl) {
             NSArray *subStringsUrl = [yourStoryUrl componentsSeparatedByString:@"/"];
             NSString *stripedName = [subStringsUrl lastObject];
             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
               NSString *documentsDirectory = [paths objectAtIndex:0];
              NSString* filePath =[documentsDirectory stringByAppendingPathComponent:      [NSString stringWithFormat:@"%@",stripedName]];
             if(filePath) {
           UIImage *image = [UIImage imageWithContentsOfFile:filePath];
                if(image) {
            ysTableViewCell  *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
            if(updateCell)
                updateCell.ThumbImage1.image=image;
            cell1.ThumbImage1.image=image;
             } else {
              dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
              dispatch_async(taskQ, ^{
                NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl];
                NSData *data =  [NSData dataWithContentsOfURL:Imageurl];
                UIImage *images1 = [[UIImage alloc] initWithData:data];
                NSData *imageData = UIImagePNGRepresentation(images1);
                if (![imageData writeToFile:filePath atomically:NO])
                {
                    NSLog((@"Failed to cache image data to disk"));
                }
                else
                {
                    NSLog(@"the cachedImagedPath is %@",filePath);
                }
                 dispatch_sync(dispatch_get_main_queue(), ^{
                    ysTableViewCell  *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
                    if(updateCell)
                        updateCell.ThumbImage1.image=images1;
                    cell1.ThumbImage1.image=images1;
                });
               });
            }

return cell1;

}

感谢您的帮助。 提前致谢。

【问题讨论】:

    标签: ios objective-c json uitableview nsurlconnection


    【解决方案1】:

    这看起来真的很乱,我建议你改变你的整个设计。

    一种基本且更干净的方式(但可能不是最好/最干净的方式):

    1. 创建类以处理视图外相关工作(此处为 JSON 解析)
    2. 在 viewDidLoad 中调用该类开始解析
    3. 调用一个方法,在解析完成时(在 JSON 类中)使用新解析的数据刷新表视图。

    这样,表格视图将首先加载您的占位符,然后在它有数据时重新加载。

    在我看来,更好的方法是在加载之前填充它,这样就没有等待时间。

    你能自己找到你需要的东西,还是单独编写代码?或者你需要帮助吗?如果有,用什么?

    编辑:您可以/应该也使用 AFNetworking 框架,使用 JSON/Internet 相关代码让您的生活轻松 10 倍。

    【讨论】:

    • @thanks Zil 我会在我的代码中应用你的建议,现在你能帮我在这段代码中实现 NSUrlConnection 吗..
    • 我刚刚编辑了我的答案,但我强烈建议您遵循有关 AFNetworking 的教程,它没有 NSUrlConnection 复杂并且可以创造奇迹。你可以在 raywenderlich (google it) 或 tutorialspoint (google it) 上找到相关帮助。如果您从头开始学习教程,这将比我对您有更多帮助,并且应该花费您大约 2 个小时。所以谷歌这个:afnetworking raywenderlich,跟着它,你会成为一个快乐的人。另外,如果它真的有帮助,请确保投票,这对我也有帮助:P
    • @感谢 Zli,我已经完成了本教程,但在实施中再次遇到问题,但我会再试一次并为你投票
    【解决方案2】:

    我通常创建一个类来处理我的数据加载,无论是来自 URL 还是本地存储。您可以使用 AFNetworking,但您可能不需要大量额外的东西。使用 NSUrlConnection 的基础非常简单。

    试试这个教程,它会帮助你在添加第三方库之前了解 Apple 的实现是如何工作的。

    NSUrlConnection Tutorial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多