imageView blank when set with URL? - ios

I'm using the below to set my imageView with a url (located in path). Yes, the URL data is returned successfully, but for some reason, my imageView remains blank (just white?)
And yes, I've hooked up my imageView property... Any idea what's wrong? Should I be using a different block of code to accomplish this?
Viewcontroller.m
NSMutableDictionary *viewParamsDogs = [NSMutableDictionary new];
[viewParamsDogs setValue:#"mydogs" forKey:#"view_name"];
[DIOSView viewGet:viewParamsDogs success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.dogData = [responseObject mutableCopy];
[operation responseString];
NSDictionary *dic = [responseObject valueForKey: #"field_pet_photo_path"];
NSArray *arr = [dic valueForKey: #"und"];
NSDictionary *dic2= [arr objectAtIndex : 0];
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSLog(#"This is path %#", path);
if([path length]>0) {
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = image;
} else {
NSString *ImageURL = #"http://url.ca/paw.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.dogimageView.image = [UIImage imageWithData:imageData];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
Path:
[5111:1673330] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
)
NSLog(#"This is path %#, %#", path, NSStringFromClass(path.class)); returns:
2016-04-14 13:18:39.590 [5225:1700657] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
), __NSCFString

I recommend usage of AFNetworking https://github.com/AFNetworking/AFNetworking for all networking connect features.
Import UIImageView+AFNetworking.h at beginning of file
#import "UIImageView+AFNetworking.h"
Get path from dic2
NSString *path = dic2[#"safe_value"];
Check if path is a string
if (![path isKindOfClass:[NSString class]]) {
return;
}
Create a NSURL object from string
NSURL *imageUrl = [NSURL URLWithString:path];
Set imageUrl to UIImageView
[self.dogimageView setImageWithURL:imageUrl];
You could check the full code in my gist https://gist.github.com/MaciejGad/fa8cb80dfc73ea55edeedb75418ea2ec
Edit:
the reason of error was the path that was set as:
NSString *path = #"(
\"http://url.com/default/files/stored/1460659054.jpg\"
)";
to change to normal URL we need to trim it:
NSMutableCharacterSet *characterSetToTrim = [NSMutableCharacterSet characterSetWithCharactersInString:#"()\""];
[characterSetToTrim formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
path = [path stringByTrimmingCharactersInSet:characterSetToTrim];
after this trimming path should be http://url.com/default/files/stored/1460659054.jpg

Try like this,
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
and You can use great library SDWebImage for caching image. When image comes from server use of this library is very helpful. Hope this will work.
Update :
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
Try this. :)

Try using dataWithContentsOfURL:options:error: instead and look if there is any error message there

Related

Need to set the image from URL without any blink. Read the description to know the complete scenario

I am uploading the image from the ImagePicker and once the image is upload on the server I show it from URL. So from local image to URL image, there comes a blink, which I want to avoid but I am unable to fix it. Any suggestion will be really helpful. I am adding the code below:
- (void)setDataOnCell:(NSDictionary *)dict {
self.messageTimeLabel.text = [CommonUtils checkForNUllValue:[dict valueForKey:#"msg_time"]];
if (![[CommonUtils checkForNUllValue:[dict valueForKey:#"msg_status"]] isEqualToString:#"Read"]) {
self.messageTickImageView.image = [UIImage imageNamed:#"check_delivered_icon"];
self.messageStatusLabel.textColor = [UIColor colorWithRed:166.0f/255.0f green:166.0f/255.0f blue:166.0f/255.0f alpha:1.0];
}
else {
self.messageTickImageView.image = [UIImage imageNamed:#"check_read_icon"];
self.messageStatusLabel.textColor = [UIColor colorWithRed:254.0f/255.0f green:223.0f/255.0f blue:224.0f/255.0f alpha:1.0];
}
self.messageStatusLabel.text = [CommonUtils checkForNUllValue:[dict valueForKey:#"msg_status"]];
if ([[NSString stringWithFormat:#"%#", [dict valueForKey:#"attachment_type"]] isEqualToString:#"local_img"]){
self.messageImageview.image = [dict valueForKey:#"attachment"];
}
else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#", [NSString stringWithFormat:#"%#", [dict valueForKey:#"attachment"]]]];
NSData *urlData = [NSData dataWithContentsOfURL:imageURL];
//This is your completion handler
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:urlData];
self.messageImageview.image = image;
});
});
}
}
first of all you need to set a default image on this image view after that you call image by url and set on this
NSOperationQueue *queueThumbnl = [[NSOperationQueue alloc] init];
[queueThumbnl setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
[queueThumbnl addOperationWithBlock:^{
// Background work
NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#", [NSString stringWithFormat:#"%#", [dict valueForKey:#"attachment"]]]];
NSData *urlData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:urlData];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:self.messageImageview, #"messageImageview", urlData, #"imageData", nil];
[self performSelectorOnMainThread:#selector(mainThreadUIUpdate:) withObject:dict waitUntilDone:YES];
// [self updateThumbnailOnMainThread:anItem setImageTo:cell];
}];
-(void)mainThreadUIUpdate:(NSDictionary *)dict
{
UIImageView *messge = [dict objectForKey:#"messageImageview"];
UIImage *image = [dict objectForKey:#"image"];
[messge.imageView setImage:image];
[cell.imageView setNeedsDisplay:YES];
}

Null value causing crash even with if/else statement?

I'm having the strangest issue. I'm using the below code to display the profile photo of a logged in user (I'm retrieving the image from a field in my Drupal database).
.m
//USER PHOTO
NSDictionary *user = [[DIOSSession sharedSession] user];
NSString *secondLink = user[#"field_photo_path"][#"und"][0][#"safe_value"];
NSLog(#"This is second link %#", secondLink);
if([secondLink length]>0) {
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
// self.imageView.image = [UIImage imageWithData:imageData];
self.imageView.image = [[UIImage alloc] initWithData:imageData];
} else {
NSString *ImageURL = #"http://url.com/default.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
}
Naturally, if secondLink is null (or empty, e.g. no photo has been uploaded), I receive the following error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArray0
objectForKeyedSubscript:]: unrecognized selector sent to instance
0x14f602fe0'
I thought I solved this issue with the if/else statement, but apparently not. How can I fix this?
Cheers!
NSString *secondLink = user[#"field_photo_path"][#"und"][0][#"safe_value"];
You need to verify that the user dictionary is valid before reading that far into it.
if (user[#"field_photo_path"]) {
// you can look for [#"und"] here
// providing it is a dictionary and not an array
if([user[#"field_photo_path"] isKindOfClass:[NSDictionary class]]){
if (user[#"field_photo_path"][#"und"]) {
// etc
}
}
}
You can reduce this nested code by modelling a User class as an NSObject subclass and include methods in that class to parse this data safely, allowing you to only write this validation code in one place.
Edit
As mentioned in a comment:
If the data in user[#"field_photo_path"][#"und"] is an NSDictionary and not an NSArray you cannot access it with [0] and will get your crash. You access NSArray's with an index (array[0], array[1] etc) and an NSDictionary with a key (dict[#"name"], dict[#"und"] etc)
Solution is to put check on on your key's
//USER PHOTO
NSDictionary *user = [[DIOSSession sharedSession] user];
if (user[#"field_photo_path"]) {
if ([user[#"field_photo_path"] isKindOfClass:[NSDictionary class]]) {
if (user[#"field_photo_path"][#"und"]) {
if ([user[#"field_photo_path"][#"und"]isKindOfClass:[NSArray class]]) {
if ([user[#"field_photo_path"][#"und"] count]>0) {
if (user[#"field_photo_path"][#"und"][0][#"safe_value"]) {
if ([user[#"field_photo_path"][#"und"][0][#"safe_value"] isKindOfClass:[NSDictionary class]]){
NSString *secondLink = user[#"field_photo_path"][#"und"][0][#"safe_value"];
NSLog(#"This is second link %#", secondLink);
if([secondLink length]>0) {
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
// self.imageView.image = [UIImage imageWithData:imageData];
self.imageView.image = [[UIImage alloc] initWithData:imageData];
} else {
NSString *ImageURL = #"http://url.com/default.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
}
}
}
}
}
}
}
}
You can also use try catch block to avoid crashing
#try {
//USER PHOTO
NSDictionary *user = [[DIOSSession sharedSession] user];
NSString *secondLink = user[#"field_photo_path"][#"und"][0][#"safe_value"];
NSLog(#"This is second link %#", secondLink);
if([secondLink length]>0) {
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
// self.imageView.image = [UIImage imageWithData:imageData];
self.imageView.image = [[UIImage alloc] initWithData:imageData];
} else {
NSString *ImageURL = #"http://url.com/default.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
}
}
#catch (NSException *exception) {
//Handle expecption
}
#finally {
}

Set NSString with returned JSON value

I'm trying to set my imageView with the url returned in the JSON data below in "value" (secondLink). When I use the following code, it returns the entire block in JSON through my XCode console - what should my code look like if I ONLY want the image's URL to be returned (right now, I assume it's trying to set the imageView with EVERYTHING returned in secondLink)?
ViewController.m
NSString *secondLink = [[[[DIOSSession sharedSession] user] objectForKey:#"field_photo_path"] objectForKey:#"safe_value"];
NSLog(#"This is second link %#", secondLink);
if([secondLink length]>0) {
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
} else {
NSString *ImageURL = #"defaulturl.com";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
}
JSON data
{
und = (
{
format = "<null>";
"safe_value" = "http://myurl.com/sites/default/files/stored/photo.jpg";
value = "http://myurl.com/sites/default/files/stored/photo.jpg";
}
);
}
In field_photo_path there is a dictionary und which contains an array.
The first item in the array is a dictionary containing the key safe_value.
It assumes that user is also a dictionary (at least it responds to objectForKey:)
NSDictionary *user = [[DIOSSession sharedSession] user];
NSString *secondLink = user[#"field_photo_path"][#"und"][0][#"safe_value"];

how to check if image is nil then load default image Xcode

i am loading an image from a url - the son is added to a dictionary and then an array is created with the image and a UIImageView uses that image. This works fine as long as the url contains an image. I know i need to check for nil and load a default image if so but i can't seem to get it to work properly. Any help would be appreciated.
NSString *string = _baseUrlString2;
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
NSDictionary *dic = (NSDictionary *)responseObject;
//NSLog(#" name %#", [dic objectForKey:#"name"]);
//NSLog(#" image %#", [dic objectForKey:#"images"]);
//NSLog(#" barcode %#", [dic objectForKey:#"barcode"]);
_data.text = [dic objectForKey:#"barcode"];
_data2.text = [dic objectForKey:#"name"];
this is where the issue is - i added a break and noted that the array contained 0 objects so i tried to make this trigger the default image but it doesn't. i also tried == nil
NSArray *picImage = [dic objectForKey:#"images"];
if ([picImage isEqual:#"0 objects"]) {
//yourImageURL is not valid
_imageView.image=[UIImage imageNamed:#"placeholder.png"];
}
else{
//yourImageURL is valid
NSString *image = [picImage objectAtIndex:0];
NSURL *url = [NSURL URLWithString: image];
_imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: url ]];
}
this is the working code but crashes if image is missing
/*
NSArray *picImage = [dic objectForKey:#"images"];
NSString *image = [picImage objectAtIndex:0];
NSURL *url = [NSURL URLWithString: image];
_imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: url ]];
*/
}
Any help is appreciated
You are comparing against its NSLog output, which is a little weird..
Replace:
if ([picImage isEqual:#"0 objects"])
With:
if ([picImage count] == 0)

Parse json data image to image view

This is my JSON response,
{
"AppConfig": {
"store_logo": "url",
"deal_status": "A",
"see_the_menu_btn": "A",
"store_id": "3",
"store_name": " Pizza Restaurant",
"bg_image": "www.my image.png"
}
}
NSString *localwthr = [NSString stringWithFormat:#"my url"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:localwthr]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (responsedata) {
NSDictionary *Dictionarydetails = [NSJSONSerialization
JSONObjectWithData:responsedata
options:kNilOptions
error:nil];
NSLog(#"The return data is: %#",Dictionarydetails);
NSString *imgURL=[[Dictionarydetails objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,100,100)];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
}
}
I need to get URL value for key bg_image, download image and set it in the UIImageView. How can I do this?
imageUrl is never like "www.my image.png",
imageUrl is like "http://www.serverName.com/directory/..../imageName.png"
if there is space in your url then you have to convert it into UTF8 format, which is a standard format for webURL.
so You should use,
imgURL = [imgURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//Use it as it shown in below code.
NSString *imgURL=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
imgURL = [imgURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
cheers!
For loading the image from the URL, then
NSString *imgURL=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
Try This:
NSString *imgURL=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,100,100)];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
check out this code , is this you are needed or not as rmaddy told post your done code as far as now
NSString *imageName=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
imageview.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imageName]]];

Resources