2012-04-20 32 views
5

Tôi có vài hình ảnh trên máy chủ có tên được lưu trữ trong bảng phpmysql. Bảng chứa hai trường: id và hình ảnh. Tôi đã chuẩn bị một php để lấy hình ảnh trong json mã hóa định dạng như đã đề cập:Làm thế nào để hiển thị mảng hình ảnh json trong UITableView bằng cách sử dụng đa luồng?

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); 

?> 

Bây giờ, khi tôi nhấn url, tôi đang nhận được phản ứng sau:

[{ "image": "./ 95462"}, {"image": "./ 8838upload_image.jpg"} {"image": "./ 43185upload_image.jpg"}, {"hình ảnh": "/ 17426upload_image.jpg"} ]

Tôi đang nhận mảng json như trên.

Bước tiếp theo là hiển thị mảng trên theo cách đa luồng trong UITableView. Tôi nhận được hình ảnh từ url khi tôi mã hóa chúng nhưng khi nói đến phân tích cú pháp json, tôi là một noob. Tôi đã thử mọi cách có thể trong đó json có thể được phân tích cú pháp để bạn tham khảo, tôi đang đăng tập tin .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); 
     } 

Tôi tin rằng điều gì đó cần được thực hiện trong phương pháp viewDidAppear nhưng tôi không hiểu điều gì.

Vui lòng giúp tôi. Tôi đã thử mọi phương pháp json có thể. Có thể tôi đang làm một số lỗi trong đó nhưng tôi tất cả các cách thất vọng. Xin hãy giúp tôi.

+0

Nếu bất cứ ai có thể tìm ra các mã nêu trên, xin vui lòng cho tôi biết xin vui lòng – madLokesh

Trả lời

2

Dude..use tài liệu tham khảo sau đây và bạn sẽ nhận được hướng dẫn như bản demo làm việc ..

images in UITableView using multithreading

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

Hope, điều này sẽ giúp bạn ...

+0

thanx tấn ví dụ như thế này là gần như chính xác những gì tôi muốn, nhưng tôi đang phải đối mặt với một số vấn đề về nơi tôi nên sử dụng ví dụ này trong mã của tôi được đăng ở trên hoặc nơi tôi nên thực hiện thay đổi trong ví dụ để làm việc theo cách của tôi. Tôi là một tổng newbie trên iOS [2 tuần kinh nghiệm] và cố gắng để có được đào tạo về cần phải biết cơ sở ... xin vui lòng giúp tôi ,,,, – madLokesh

+0

@LokeshBhatija: Đối với newbie nói dối bạn nó không phải là một nhiệm vụ dễ dàng để làm .. Vì vậy, tôi đề nghị bạn đi qua các bài báo bot và đọc nó .. Tôi cũng đã thêm tài liệu tham khảo mới. – Nit

+0

chương trình markofjohnson cũ. Tôi đã trải qua điều này. HJCache đang gây ra lỗi. Tôi sẽ sớm đăng những lỗi đó. Trong thời gian có nghĩa là tôi sẽ làm việc trên các tài liệu tham khảo trước u đề cập đến – madLokesh

2

tôi đề nghị bạn để sử dụng SDWebImage

Hình ảnh web Thư viện này cung cấp một danh mục cho UIImageVIew với sự hỗ trợ cho hình ảnh từ xa đến từ web.

Nó cung cấp:

Một loại UIImageView thêm hình ảnh web và quản lý bộ nhớ cache để khuôn khổ Cocoa Touch Một hình ảnh không đồng bộ downloader Một bộ nhớ + ảnh đĩa không đồng bộ bộ nhớ đệm với xử lý Một đảm bảo hết hạn bộ nhớ cache tự động cùng một URL sẽ không được tải xuống nhiều lần Đảm bảo rằng các URL không có thật sẽ không được thử lại một lần nữa và một lần nữa Biểu diễn!

+0

bạn có thể cung cấp cho tôi một số ví dụ về cùng một dòng bằng sdwebview hay không. – madLokesh

1
+0

bạn có thể giúp tôi với các ví dụ trực tiếp tương tự như [link] (http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial). Tôi cần điều tương tự nhưng sự khác biệt là tôi cần mảng hình ảnh từ máy chủ localhost thay vì một trang web. – madLokesh

Các vấn đề liên quan