2014-11-05 19 views
0

下午好,的TableView控制器使用JSON NSURL

我試圖使用的TableView控制器來顯示從我的MySQL數據庫項目的X個,但我此刻有點失落。

我有另外一個項目中,我可以展示使用JSON輸出數據的數據,但我不知道如何代碼添加到我的項目,以便從我的數據庫顯示數據。這是我使用的代碼:

@implementation HomeModel 

- (void)downloadItems 
{ 
    // Download the json file 
    NSURL *jsonFileUrl = [NSURL URLWithString:@"http://website.com/service.php"]; 

    // Create the request 
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl]; 

    // Create the NSURLConnection 
    [NSURLConnection connectionWithRequest:urlRequest delegate:self]; 
} 

#pragma mark NSURLConnectionDataProtocol Methods 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    // Initialize the data object 
    _downloadedData = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    // Append the newly downloaded data 
    [_downloadedData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // Create an array to store the locations 
    NSMutableArray *_locations = [[NSMutableArray alloc] init]; 

    // Parse the JSON that came in 
    NSError *error; 
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error]; 

    // Loop through Json objects, create question objects and add them to our questions array 
    for (int i = 0; i < jsonArray.count; i++) 
    { 
     NSDictionary *jsonElement = jsonArray[i]; 

     // Create a new location object and set its props to JsonElement properties 
     Location *newLocation = [[Location alloc] init]; 
     newLocation.name = jsonElement[@"user"]; 
     newLocation.address = jsonElement[@"imagen"]; 
     newLocation.latitude = jsonElement[@"date"]; 

     // Add this question to the locations array 
     [_locations addObject:newLocation]; 
    } 

    // Ready to notify delegate that data is ready and pass back items 
    if (self.delegate) 
    { 
     [self.delegate itemsDownloaded:_locations]; 
    } 
} 

@end 

目前這是我的代碼:

TableViewController.m

#import "CarTableViewController.h" 
#import "CarTableViewCell.h" 
#import "CarTableViewController.h" 
#import "CarDetailViewController.h" 

@implementation CarTableViewController 

@synthesize carMakes = _carMakes; 
@synthesize carModels = _carModels; 
@synthesize carImages = _carImages; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.carMakes = [[NSArray alloc] 
        initWithObjects:@"Chevy", 
        @"BMW", 
        @"Toyota", 
        @"Volvo", 
        @"Smart", nil]; 

    self.carModels = [[NSArray alloc] 
         initWithObjects:@"Volt", 
         @"Mini", 
         @"Venza", 
         @"S60", 
         @"Fortwo", nil]; 

    self.carImages = [[NSArray alloc] 
         initWithObjects:@"chevy_volt.jpg", 
         @"mini_clubman.jpg", 
         @"toyota_venza.jpg", 
         @"volvo_s60.jpg", 
         @"smart_fortwo.jpg", nil]; 
} 

- (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.carModels count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"carTableCell"; 

    CarTableViewCell *cell = [tableView 
           dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[CarTableViewCell alloc] 
       initWithStyle:UITableViewCellStyleDefault 
       reuseIdentifier:CellIdentifier]; 
    } 

    // Configure the cell... 
    cell.makeLabel.text = [self.carMakes 
          objectAtIndex: [indexPath row]]; 

    cell.modelLabel.text = [self.carModels 
          objectAtIndex:[indexPath row]]; 

    UIImage *carPhoto = [UIImage imageNamed: 
         [self.carImages objectAtIndex: [indexPath row]]]; 

    cell.carImage.image = carPhoto; 

    return cell; 
} 

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if ([[segue identifier] isEqualToString:@"ShowCarDetails"]) 
    { 
     CarDetailViewController *detailViewController = 
     [segue destinationViewController]; 

     NSIndexPath *myIndexPath = [self.tableView 
            indexPathForSelectedRow]; 

     detailViewController.carDetailModel = [[NSArray alloc] 
               initWithObjects: [self.carMakes 
                   objectAtIndex:[myIndexPath row]], 
               [self.carModels objectAtIndex:[myIndexPath row]], 
               [self.carImages objectAtIndex:[myIndexPath row]], 
               nil]; 
    } 
} 

@end 

TableViewController.h

#import <UIKit/UIKit.h> 

@interface CarTableViewController : UITableViewController 

@property (nonatomic, strong) NSArray *carImages; 
@property (nonatomic, strong) NSArray *carMakes; 
@property (nonatomic, strong) NSArray *carModels; 

@end 

如何添加第一代碼(從我的數據庫結果)到另一個項目?我現在迷失了,如果你能給我一些關於這個問題的信息,我會很感激,因爲我想編輯故事板上的信息,就像我在第二個項目中一樣。

在此先感謝。

問候。

在此先感謝。

回答

1

這是因爲你不直接從你的iPhone連接到數據庫。一般來說,你有一個Web服務(也稱爲API)來公開你的數據(例如JSON格式)。因此,您必須在PHP,Ruby或Node中構建一個API,以暴露數據庫的數據並訪問它。

編輯:

什麼,我看到的是你的HomeModel,你可以設置一個委託,該委託有一個函數itemsDownloaded,您通過您的API中的數據得到。

所以,你希望你的CarTableViewController到是委託接收這些數據。

首先,你必須有一個對象HomeModel,在您的TableViewController.h加:

@property (strong, nonatomic) HomeModel *homeModel; 

現在你必須調用,從服務器獲取數據的代碼。喜歡的東西

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    homeModel = [HomeModel new]; 
    homeModel.delegate = self; 
    [homeModel downloadItems]; 
} 

最後,你有你的CarTableViewController實施itemsDownloaded。做這樣的事情:

- (void)itemsDownloaded:(NSArray *)items 
{ 
    self.carMakes = items; // Problem here 
    [self.tableView reloadData];  
} 

但問題是HomeModel解析東西從你在carMakes什麼不同,你必須適應在HomeModelLoop through Json objects。 你可能想嘗試AFNetworking這是一個比NSURLConnection更容易使用的庫。

+0

Hi @Jonathan Tribouharet。我已經構建了該PHP文件,並且我有一個JSON輸出,還有一個xcode項目在TableView中顯示了該JSON的結果,但現在我需要將該數據傳遞給一個segue,而且我無法做到這一點。 – JulienKP 2014-11-05 21:14:21

+0

你想從你的UITableViewController傳遞一些日期到你的CarDetailViewController?什麼在你的代碼中不起作用? – 2014-11-05 21:32:55

+0

問題是在我的代碼中,我編寫了靜態代碼,現在我想用我的輸出JSON的結果寫入數組。我怎樣才能做到這一點? – JulienKP 2014-11-05 21:42:16

相關問題