2
如何使用objective-C將數據發送到iOS中的tableview?我試圖解決我的問題很長時間,但結果不正確。我的tableview仍然是空的。我做錯了什麼?以下是我的實現文件。將數據從Google Places API發送到桌面視圖
import "PlacesViewController.h"
@implementation PlacesViewController
@synthesize places;
- (void)viewDidLoad
{
[super viewDidLoad];
// Set this view controller object as the delegate and data source for the table view
self.listTableView.delegate = self;
self.listTableView.dataSource = self;
}
-(void)queryGooglePlaces
{
//Build the url string to send to Google
NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.503186,-0.126446&radius=5000&[email protected]|restaurant|bar&keyword=vegetarian&key=myOwnKEY"];
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];
dispatch_sync(dispatch_get_main_queue(), ^{
[self fetchedData:data];
});
});
}
-(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".
self.places = [json objectForKey:@"results"];
//Write out the data to the console.
NSLog(@"Google Data: %@", json);
}
#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"];
return cell;
}
@end
謝謝。但我無法嘗試你的解決方案,因爲我有新的問題。我看到「線程1:斷點3.1」在線排隊以返回tableview中的部分行數:return [self.places count] ;.你知道爲什麼嗎? – Luki
這意味着結果'[json objectForKey:@「結果」]'不是'NSArray',請NSLog和檢查請求結果 – l0gg3r
我只更改NSLog(@「Google Data:%@」,json);到NSLog(@「Google Data:%@」,地點);和「線程」的問題失望了。但我的tableview仍然是空的... – Luki