将API数据发送到ViewController中的UITableView [英] Sending API Data to UITableView Within ViewController

查看:40
本文介绍了将API数据发送到ViewController中的UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Google Places API的数据填充ViewController(而不是TableViewController)中的TableView时遇到麻烦.

Having trouble filling a TableView within a ViewController (not a TableViewController) with data from the Google Places API.

我已经成功提取数据并将JSON解析为带有批注的MKMapView,所以我知道该部分正在工作,但是我希望数据也能流到它下面的表中(见照片).

I'm already pulling data successfully and parsing the JSON to a MKMapView with annotations, so I know that part's working, but I want the data to also flow into the table below it (see photo).

我到处都在寻找有关如何执行此操作的简单说明.甚至遵循了一个教程(但这是为TableViewController设计的,所以我希望我的问题就是我将其链接的方式).另一种可能性是放置我的 [self.tableView reloadData]; 调用.这对我来说是合乎逻辑的,但很可能在错误的地方.显然,如果不在正确的位置,TableView将保持空白,但是我已经在几个地方尝试过.

I've looked everywhere for a simple explanation of how to do this. Even followed a tutorial (but it was meant for a TableViewController, so I'm hoping my issue is just the way I've linked it). Another possibility is the placement of my [self.tableView reloadData]; call. It made logical sense to me, but could very well be in the wrong place. Apparently the TableView will remain blank if that's not in the right spot, but I've tried it in several places.

注意:我只包含了相关代码,希望可以使你们更容易发现.TableView对象连接到ViewController作为其数据源和委托,原型单元在属性编辑器中称为单元",如#pragma代码中所述,JSON数据存储在称为"places"的NSArray中.请让我知道,如果您发现我错过的一些愚蠢的东西导致它无法正常工作,请先感谢.

Note: I've only included the pertaining code to hopefully make it easier for you guys to spot. The TableView object is connected to the ViewController as its data source and delegate, the prototype cell is called "Cell" in the Attribute Editor as called in the #pragma code, and the JSON data is being stored in an NSArray called "places". Please let me know if you spot something stupid that I've missed that's causing this to not work and thanks in advance.

@interface RendezvousViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic)          NSArray *places;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

ViewController.m

    -(void)viewDidLoad {
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
}    

    -(void) queryGooglePlaces: (NSString *) googleType {
            // Build the url string to send to Google.
            NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=%@&types=food|restaurant|bar&sensor=true&keyword=%@&key=%@",currentCentre.latitude,currentC

entre.longitude,[NSString stringWithFormat:@"%i",currenDist],selection, kGOOGLE_API_KEY];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        NSLog(@"%@", url);

        //Formulate the string as a URL object.
        NSURL *googleRequestURL=[NSURL URLWithString:url];

        // Retrieve the results of the URL.
        dispatch_async(kBgQueue, ^{
            NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
            [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];

        });
    }

        -(void)fetchedData:(NSData *)responseData {
            //parse out the json data
            NSError* error;
            NSDictionary* json = [NSJSONSerialization
                                  JSONObjectWithData:responseData

                                  options:kNilOptions
                                  error:&error];

            //The results from Google will be an array obtained from the NSDictionary object with the key "results".
            NSArray* places = [json objectForKey:@"results"];

            //Write out the data to the console.
            NSLog(@"Google Data: %@", places);

            [self plotPositions:places];
            [self.tableView reloadData];
        }

    #pragma mark - Table view data source

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Return the number of sections.
        return 1;
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        // Return the number of rows in the section.
        return [self.places count];
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

        NSDictionary *tempDictionary= [self.places objectAtIndex:indexPath.row];

        cell.textLabel.text = [tempDictionary objectForKey:@"name"];

        if([tempDictionary objectForKey:@"rating"] != NULL)
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"Rating: %@ of 5",[tempDictionary   objectForKey:@"rating"]];
        }
        else
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"Not Rated"];
        }

        return cell;
    }

推荐答案

看起来像您的 dispatch_async 调用遇到了一些问题.

Looks like your dispatch_async call got some problem.

现在,一旦获得数据,就应该在 mainThread 中填充它.

Now Once you get the data, you should populate it from within the mainThread.

您必须将呼叫修改为:

dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self fetchedData:data];
    });
});

这将确保仅当您在后台线程中从Google加载数据完成后,才会调用 [self fetchedData:data]; .

This will ensure that [self fetchedData:data]; is called only when you are done with load data from google in background thread.

这是我的直播a>示例.

代码中也存在一个错误:将 NSArray * places = [json objectForKey:@"results"]; 更改为 self.places = [json objectForKey:@"results"]; .

Also there's a bug in the code: Change this NSArray* places = [json objectForKey:@"results"]; to self.places = [json objectForKey:@"results"];.

希望有帮助.

这篇关于将API数据发送到ViewController中的UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆