Loading an image with a variable url?

I'm new to this, so please leave this to me. I was looking for an Objective-C iPhone app and hit the road block.

I am trying to pass the value contained in a variable (string) to a method, but it doesn't work. I'm guessing this is because the variable is probably a pointer to a value, not the value itself. I wonder if you can suggest how I fix it.

Here is the method

- (UIImage *)newUIImageWithURLString:(NSString *)urlString
{
   return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]];
}

      

Sending this post works ... Here's where I hardcoded the url to submit.

UIImage* newimage = [self newUIImageWithURLString:@"http://images.mydomain.com/PhotoServer/Thumb/97/83358897.jpg"];

      

It's not ... This is where the variable is passed. I get an error the value passed is irrelevant.

UIImage* newimage = [self newUIImageWithURLString:newListing.ListingPhotoUrl];

      

I know it matters how the following works.

self.ListingtitleLabel.text = newListing.ListingPhotoUrl;

      

Any thoughts?

+1


source to share


1 answer


Are you sure the dynamic url is valid? For example, if newListing.ListingPhotoURL is not a valid URL or is not available, you will receive this error because you are not doing error checking. While your code is concise, you should probably be a little more verbose while debugging, or at least until you're more comfortable with the language. I would suggest rewriting your method as such:

-(UIImage*)newUIImageWithURLString:(NSString*)urlString {
  NSParameterAssert(urlString);
  NSData *pictureData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
  NSAssert1(pictureData, @"No data returned for url: %@", urlString);
  return [[UIImage alloc] initWithData:pictureData];
}

      



With a method written like this, you immediately know that something is not as expected (assertion macros will throw exceptions). It also gives you more detailed places to set breakpoints if you are trying to debug something.

+2


source







All Articles