2012-04-20 36 views
5

我的服務器上有幾個圖像,其名稱存儲在phpmysql表中。該表包含兩個字段:id和圖像。我已經準備了一個PHP獲取JSON中的圖像編碼的格式爲提到:如何使用多線程在UITableView中顯示json圖像數組?

jsonFetch.php

<?php 
$dbhost = "localhost"; 
$dbname = "userauth"; 
$dbuser = "root"; 
//$DB_Pass = "root"; 
$dbtable = "images"; 

@mysql_connect($dbhost, $dbuser); 
$db = mysql_select_db($dbname); 


$sql = "SELECT * FROM $dbtable"; 
$query = mysql_query($sql); 

while($row = mysql_fetch_array($query)) 
    { 
     $rows[] = array(
     //"id" => $row[0], 
     "image" => $row[1] 
     //"description" => $row['description']); 
     ); 
    } 

$json = json_encode($rows); 
$callback = $_GET['images']; 
echo $callback.$json ; 
//print_r($json); 

?> 

現在,當我打的網址,我得到如下回應:

[{ 「圖像」: 「./ 95462 」},{「 圖像 」:「 ./ 8838upload_image.jpg 」} {「 圖像 」:「 ./ 43185upload_image.jpg 」},{「 圖像 」:「/ 17426upload_image.jpg」} ]

我得到了如上所述的json數組。

下一步是在UITableView中以多線程方式顯示上述數組。 我從url獲取圖像時,我硬編碼他們,但當涉及到json解析,我是一個noob。我已經嘗試了json可以被解析的所有可能的方式,以便您參考,我發佈了.m文件。 :

#import "json.h" 

@interface profilePhotos(Private) 
- (void) initialize; 
- (void) loadImage:(id)arg; 
- (void) updateTableView:(id)arg; 
- (void) addImagesToQueue:(NSArray *)images; 
- (void) addImagesToQueue:(NSArray *)arrayImages; 
- (void) addImagesToQueue:(NSArray *)arrayDataFromServer; 
- (void) showcommentView; 
- (void) hidecommentView; 
@end 

@implementation profilePhotos 
@synthesize photosTable; 
@synthesize addPhotos; 
@synthesize deletePhotos; 
@synthesize back; 
@synthesize imageQueue, loadedImages, imageLoaderOpQueue, commentView; 
//@synthesize photosView; 


-(void)initializeWith:(int)buttonTag{ 

tag = buttonTag; 

NSLog(@"tag = %d", tag); 
} 

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    if (!(self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { 
    return self; 
    } 

[self initialize]; 
return self; 
    } 

- (void) awakeFromNib 
{ 
    NSLog(@"AsyncImageLoadingViewController::awakeFromNib called"); 
    [super awakeFromNib]; 
    [self initialize]; 
    } 

- (void) viewDidLoad 
{ 
NSLog(@"AsyncImageLoadingViewController::viewDidLoad called"); 
[super viewDidLoad]; 
} 

- (void) viewDidAppear:(BOOL)animated 
{ 
NSLog(@"AsyncImageLoadingViewController::viewDidAppear called"); 
[super viewDidAppear:animated]; 


NSArray *images = [NSArray arrayWithObjects: 
        @"http://dl.dropbox.com/u/9234555/avatars/ava01.gif", 
        @"http://dl.dropbox.com/u/9234555/avatars/ava02.gif", 
        @"http://dl.dropbox.com/u/9234555/avatars/ava03.gif", 
        @"http://dl.dropbox.com/u/9234555/avatars/ava04.gif", 
        @"http://dl.dropbox.com/u/9234555/avatars/ava05.gif", nil]; 

[self addImagesToQueue:images]; 
NSLog(@"addImagesToQueue: %@",self); 


} 


#pragma mark - 
#pragma mark Private Methods 

    /*! 
    @method  
    @abstract initializes class variables 
    */ 
- (void) initialize 
    { 
     NSLog(@"AsyncImageLoadingViewController::initialize called"); 

     NSMutableArray *a = [[NSMutableArray alloc] init]; 
     self.imageQueue = a; 
     //[a release]; 

     a = [[NSMutableArray alloc] init]; 
     self.loadedImages = a; 
     //[a release]; 

     NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
     self.imageLoaderOpQueue = queue; 
     //[queue release]; 
     } 

     /*! 
     @method  
     @abstract updates tableview for the newly downloaded image and scrolls the   tableview to bottom 
     */ 
    - (void) updateTableView:(id)arg 
     { 
     NSLog(@"AsyncImageLoadingViewController::updateTableView called"); 

     if ((arg == nil) || ([arg isKindOfClass:[UIImage class]] == NO)) { 
      return; 
    } 

    // store the newly downloaded image 
    [self.loadedImages addObject:arg]; 
    //[arg release]; 

    // refresh tableview 
    [self.photosTable reloadData]; 

    // scroll to the last cell of the tableview 
    NSIndexPath *lastRow = [NSIndexPath indexPathForRow:([self.loadedImages count] - 1) inSection:0]; 
    [self.photosTable scrollToRowAtIndexPath:lastRow 
          atScrollPosition:UITableViewScrollPositionBottom 
            animated:YES]; 
} 

/*! 
@method  
@abstract downloads images, this is the method that dispatches tasks in the operation q ueue 
*/ 
- (void) loadImage:(id)arg 
{ 
    NSLog(@"AsyncImageLoadingViewController::loadImage called"); 

    if ((arg == nil) || ([arg isKindOfClass:[NSString class]] == NO)) { 
    return; 
    } 

    // create a local autorelease pool since this code runs not on main thread 
    //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // fetch the image 
    NSLog(@"AsyncImageLoadingViewController::loadImage - will download image: %@", arg); 
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:arg]]; 
    UIImage *image = [UIImage imageWithData:data]; 
    NSLog(@"image: %@",image); 

    // update tableview with the downloaded image on main thread 
    [self performSelectorOnMainThread:@selector(updateTableView:) withObject:image waitUntilDone:NO]; 

    //[pool release]; 
    } 

    /*! 
    @method  
    @abstract adds images to the queue and starts the operation queue to download them 
    */ 
- (void) addImagesToQueue:(NSArray *)images 
    { 
    NSLog(@"AsyncImageLoadingViewController::addImagesToQueue called"); 

    [self.imageQueue addObjectsFromArray:images]; 
    NSLog(@"addImagesToQueue Array: %@", self); 

    // suspend the operation queue 
    [self.imageLoaderOpQueue setSuspended:YES]; 

    // add tasks to the operation queue 
    for (NSString *imageUrl in self.imageQueue) { 
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self            selector:@selector(loadImage:) object:imageUrl]; 
     [self.imageLoaderOpQueue addOperation:op]; 
     // [op release]; 
     } 

// clear items in the queue and resume the operation queue to start downloading images 
[self.imageQueue removeAllObjects]; 
[self.imageLoaderOpQueue setSuspended:NO]; 
    } 


#pragma mark - 
#pragma mark UITableViewDataSource Methods 

    - (NSInteger)tableView:(UITableView *)tableView 
    numberOfRowsInSection:(NSInteger)section 
    { 

return [self.loadedImages count]; 



     } 

    - (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath 
     { 

    static NSString *CellIdentifier = @"CellIdentifier"; 

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) 
{  
    //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped  reuseIdentifier:CellIdentifier] autorelease]; 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:[NSString stringWithFormat:@"cellID%d",indexPath.row]]; 

    cell.accessoryType =UITableViewCellAccessoryNone; 
    //cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator; 




    } 

for(UIView *subviews in cell.subviews) 
    [subviews removeFromSuperview]; 


    UIImageView *photo; 
    photo=[[UIImageView alloc] init]; 
    [photo setImage:[self.loadedImages objectAtIndex:indexPath.row]]; 
    [photo setFrame:CGRectMake(0, 5, 150, 120)]; 
    [cell addSubview:photo]; 
    return cell; 
     } 





    -(void)aMethod:(UIButton *)sender{ 

//[sender tag]; 

NSIndexPath *indexPath = [photosTable indexPathForCell: (UITableViewCell*)[[sender superview]superview]]; 

NSLog(@"[sender tag] is %d",[sender tag]); 



if([sender tag]==indexPath.row){ 

    textField = (UITextField*)[cell viewWithTag:[sender tag]]; 
    textField.hidden=NO; 
    } 
    //} 


    } 



#pragma mark - 
#pragma mark UITableViewDelegate Methods 

-(void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

[tableView deselectRowAtIndexPath:indexPath animated:YES]; 


} 




- (void)didReceiveMemoryWarning 
    { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
    } 

    - (void)viewDidUnload{ 
    // [self setPhotosView:nil]; 
    [self setPhotosTable:nil]; 
    [self setAddPhotos:nil]; 
    [self setDeletePhotos:nil]; 
    [self setBack:nil]; 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
     } 

    - (BOOL)shouldAutorotateToInterfaceOrientation:( UIInterfaceOrientation)interfaceOrientation 
     { 
     // Return YES for supported orientations 
     return (interfaceOrientation == UIInterfaceOrientationPortrait); 
     } 

我相信需要在viewDidAppear方法中做些什麼,但是它是什麼,我不明白。

請幫助我。我已經嘗試了所有可能的json方法。可能是我犯了一些錯誤,但我一直都很沮喪。請幫助我。

+0

如果有人能找出上述代碼,請請讓我知道請 – madLokesh 2012-04-21 09:15:12

回答

2

Dude..use以下引用,你會得到教程的工作演示..

images in UITableView using multithreading

See this reference if you are new in iOS. It's simple

希望,這將幫助你......

+0

感謝名單一噸的例子,因爲這是幾乎正是我想要的,但我面對某些關於我應該在上面發佈的代碼中使用此示例的位置的問題,或者我應該在示例本身中進行更改以便按我的方式工作的問題。我是iOS上的新手[2周的經驗],並試圖接受培訓,需要知道的基礎......請幫助我,,,,, – madLokesh 2012-04-20 07:46:23

+0

@LokeshBhatija:對於新手說謊你這不是一件容易的事情..所以,我建議你閱讀bot文章並閱讀它。我還添加了新的參考。 – Nit 2012-04-20 08:17:29

+0

老markofjohnson計劃。我已經通過這個。 HJCache導致錯誤。我將很快發佈這些錯誤。在此期間,我將工作在前面的參考你提到 – madLokesh 2012-04-20 09:29:22

2

我建議你使用SDWebImage

Web Image 此庫提供UIImageVIew的一個類別,支持來自網絡的遠程圖像。

它提供:

一個的UIImageView類別添加Web圖像和高速緩存管理的可可觸摸框架 異步圖像下載 異步存儲器+磁盤映像的高速緩存具有自動緩存過期處理 甲保證相同的URL將不會被多次下載 保證僞造的URL不會一次又一次地重試 表演!

+0

你能否給我提供一些使用sdwebview的同一行的例子。 – madLokesh 2012-04-20 07:17:25

1
+0

你能幫我解決一些類似於[link](http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial)的實例。我需要相同的東西,但不同的是,我需要從本地服務器,而不是一個網頁的圖像數組。 – madLokesh 2012-04-20 07:21:05

相關問題