0

I try to assign an image loaded via

[UIImage imageWithData: [NSData dataWithContentsOfURL:imageUrl]];

to my navigationbar. Here is what i have:

   //Loading Image from Url and adding it to navigationbar
    NSString *urlString = [NSString stringWithFormat:@"http://someurl.com/%@.gif",imageId];
    NSURL *imageUrl = [NSURL URLWithString:urlString];
    UIImage *myImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:imageUrl]];
    UIButton* button = (UIButton *) myImage;
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = buttonItem;

This works as long as i take a local image and allocate the image view like this:

UIButton* button = (UIButton *) [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myLocalImage.png"]];

The error i get is: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage _setAppearanceIsInvalid:]: unrecognized selector sent to instance 0x6876df0'

Anybody can help? (Or is this too nasty of a hack anyway?) Thanks a lot!

Ps: heres the original question for the adding image to navigation bar: how to display an image in the navigation bar of an iPhone application?

Edit: Theres an error in the code: Should be like this i guess:

UIButton* button = (UIButton *) [[UIImageview alloc] initWithImage:myImage];

Anyway, i dont get an error anymore now, but the image does not appear...

IPS Brar
  • 346
  • 1
  • 14
Riscie
  • 3,775
  • 1
  • 24
  • 31

2 Answers2

1

This should work asynchronously

UIButton *button = [UIButton alloc] init];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button]; 
self.navigationItem.rightBarButtonItem = barButtonItem;

__block UIImage *image;
// create a dispatch queue to download your image asynchronously
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
// show network activity indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
 dispatch_async(downloadQueue, ^{
        image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
        // dispatch to the main queue
        dispatch_sync(dispatch_get_main_queue(), ^{
                // set your button's image
                [button setImage:image forState:UIControlStateNormal];
            });
        }
});
    dispatch_release(downloadQueue);
// hide network activity indicator
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
Moxy
  • 4,162
  • 2
  • 30
  • 49
0

Got it. Had this code in a seperate thread and i guess this is not working after the view is already loaded. If i put it plain to vieDidLoad then it works...

You'll get enlighted as soon as you post here... ^^

Riscie
  • 3,775
  • 1
  • 24
  • 31