AsyncImage получить изображение из исходного кода программы? - PullRequest
0 голосов
/ 19 апреля 2011

из этого кода

#import "AsyncImageView.h"
#import "ImageCache.h"
#import "ImageCacheObject.h"

static ImageCache *imageCache = nil;

@implementation AsyncImageView


- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}


- (void)drawRect:(CGRect)rect {
    // Drawing code
}


- (void)dealloc {
    [connection cancel];
    [connection release];
    [data release];
    [super dealloc];
}

-(void)loadImageFromURL:(NSURL*)url {
    if (connection != nil) {
        [connection cancel];
        [connection release];
        connection = nil;
    }
    if (data != nil) {
        [data release];
        data = nil;
    }

    if (imageCache == nil) 
        imageCache = [[ImageCache alloc] initWithMaxSize:2*1024*1024]; 

    [urlString release];
    urlString = [[url absoluteString] copy];
    UIImage *cachedImage = [imageCache imageForKey:urlString];
    if (cachedImage != nil) 
    {   NSLog(@"get in");
        if ([[self subviews] count] > 0) 
        {
            [[[self subviews] objectAtIndex:0] removeFromSuperview];
        }
        UIImageView *imageView = [[[UIImageView alloc] initWithImage:cachedImage] autorelease];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.autoresizingMask = 
        UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self addSubview:imageView];
        imageView.frame = self.bounds;
        [imageView setNeedsLayout]; 
        [self setNeedsLayout];
        return;
    }

#define SPINNY_TAG 5555   

    UIActivityIndicatorView *spinny = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinny.tag = SPINNY_TAG;
    spinny.center = self.center;
    [spinny startAnimating];
    [self addSubview:spinny];
    [spinny release];

    NSURLRequest *request = [NSURLRequest requestWithURL:url 
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                         timeoutInterval:60.0];
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection 
    didReceiveData:(NSData *)incrementalData {
    if (data==nil) {
        data = [[NSMutableData alloc] initWithCapacity:2048];
    }
    [data appendData:incrementalData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
    [connection release];
    connection = nil;

    UIView *spinny = [self viewWithTag:SPINNY_TAG];
    [spinny removeFromSuperview];

    if ([[self subviews] count] > 0) {
        [[[self subviews] objectAtIndex:0] removeFromSuperview];
    }

    UIImage *image = [UIImage imageWithData:data];

    [imageCache insertImage:image withSize:[data length] forKey:urlString];

    UIImageView *imageView = [[[UIImageView alloc] 
                               initWithImage:image] autorelease];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.autoresizingMask = 
    UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:imageView];
    imageView.frame = self.bounds;
    [imageView setNeedsLayout]; // is this necessary if superview gets setNeedsLayout?
    [self setNeedsLayout];
    [data release];
    data = nil;
}

@end

Если я хочу получить изображение из исходного кода приложения, если URL-адрес пуст, какой код я должен добавить ??

и вот еще код от xyz.m

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

    UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:
                             CellIdentifier];
    if (cell == nil) {
        //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell = [self getCellContentView:CellIdentifier];
    }
    else{
        AsyncImageView *oldImage = (AsyncImageView *)[cell.contentView viewWithTag:999];
        [oldImage removeFromSuperview];
    }
    int index = [indexPath indexAtPosition: [indexPath length] - 1];

    //Get Picture
    CGRect frame;
    frame.size.width=50; frame.size.height=50;
    frame.origin.x=10; frame.origin.y=0;
    AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
    asyncImage.tag = 999;

    NSString *string = [jsonPic objectAtIndex:index];
    NSString *url=[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSURL *imageURL = [NSURL URLWithString:url];
    if([string isEqualToString:@""]){
     NSLog(@"Not found");

здесь я не знаю Как я могу получить изображение из источника

        AsyncImageView * NoImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
        NoImage.tag = 999;
        NoImage.image = [UIImage imageNamed:@"bl-noImg.gif"];
        [cell.contentView addSubview:NoImage];
    }
    else
    {   NSLog(@"image  URL %@",imageURL);
       [asyncImage loadImageFromURL:imageURL];
        [cell.contentView addSubview:asyncImage];

Я могу получить изображение из asyncImage

Пожалуйста, помогите мне или помогитемне сделать это.благодарю вас .,,,Теперь все готово, и вот мой код результата

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

    UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:
                             CellIdentifier];
    if (cell == nil) {
        //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell = [self getCellContentView:CellIdentifier];
    }
    else{
        AsyncImageView *oldImage = (AsyncImageView *)[cell.contentView viewWithTag:999];
        [oldImage removeFromSuperview];
    }
    int index = [indexPath indexAtPosition: [indexPath length] - 1];

    //Get Picture
    CGRect frame;
    frame.size.width=50; frame.size.height=50;
    frame.origin.x=10; frame.origin.y=0;
    AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
    asyncImage.tag = 999;

    NSString *string = [jsonPic objectAtIndex:index];
     if([string isEqualToString:@""]){
     //NSLog(@"Not found");
        UIImageView * NoImg = [[[UIImageView alloc] initWithFrame:frame] autorelease];
        NoImg.tag = 999;
        [NoImg setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg-noImg" ofType:@"gif"]]];
        [cell.contentView addSubview:NoImg];
    }
    else
    {   //NSLog(@"image  URL %@",imageURL);
        NSString *url=[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSURL *imageURL = [NSURL URLWithString:url];
        [asyncImage loadImageFromURL:imageURL];
        [cell.contentView addSubview:asyncImage];
    }

спасибо всем:)

1 Ответ

0 голосов
/ 19 апреля 2011

Если вы проверяете наличие пустого URL, то вы должны проверить его перед вызовом loadImageFromURL и даже перед созданием объекта NSURL.Если он не пустой, то вы должны создать объект NSURL и вызвать метод loadImageFromURL.

где-то в вашем коде ... откуда вы вызываете loadImageFromURL:

    if(urlString !=nil || [urlString length]>0)
    {
     create NSURL object
     now again check NSURL object whether its nil or not
     we are checking it because if the urlString has incorrect url pattern then no
 NSURLObject would be created, so if there is no NSURLObject then we should not call
 your method.
     if(NSURLObject !=nil)
     {
        call loadImageFromURL method and so on
     }
     else
     {
       //load some default image. which will convey no URL Found
     }

    }
    else
     {
       //load some default image. which will convey no URL Found
     }

Спасибо,

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...