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)
Related
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];
}
Here is what I have tried so far:
-(void)postMethod_Param
{
NSString *urlString=#"http://192.168.1.139:49/api//Grievance/PostCreateRequest";
NSString *bodydata =[NSString stringWithFormat:#"&user_fb_id=%#&status=%d",fbUserId,status];
}
If you want to post data to server
Pick Image from Gallery and save it to array
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image=[info objectForKey:#"UIImagePickerControllerOriginalImage"];
imageView.image=image;
[arrayImage addObject:image];
picker.delegate =self;
[picker dismissViewControllerAnimated:YES completion:nil];
}
For saving image as path and also convert into path as string
for (UIImage *img in array_Image)
{
int i=0;
NSString *pathName =nil;
NSString *file_name = [[self getCurrentDate]stringByAppendingString:[self getCurrentTime]];
file_name =[file_name stringByAppendingPathExtension:#"jpeg"];
NSArray *paths1 =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath =([paths1 count] >i) ? [paths1 objectAtIndex:i] : nil;
NSString *path = [basePath stringByAppendingPathComponent:#"Photo"];
//Get Directory in FileManager
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path])
return;
[fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
pathName =[path stringByAppendingPathComponent:file_name];
NSData *imgData =UIImageJPEGRepresentation(image, 0.4);
[imgData writeToFile:pathName atomically:YES];
[arryImagePath addObject:pathName];
}
I Call the below methods in file_name
+(NSString*)getCurrentTime
{
//Get Current Time for saving Images
NSString *path =nil;
NSDateFormatter *timeFormatter =[[NSDateFormatter alloc]init];
[timeFormatter setDateFormat:#"HH:mm:ss.SSS"];
NSDate *now = [[NSDate alloc]init];
NSString *str_time = [timeFormatter stringFromDate:now];
NSString *curr_time;
curr_time =[str_time stringByReplacingOccurrencesOfString:#"." withString:#""];
path = [NSString stringWithFormat:#"%#",curr_time];
return path;
}
+(NSString*)getCurrentDate
{
NSString *today =nil;
NSDateFormatter *dateFormatter1;
dateFormatter1 =[[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:#"d MMM yyyy"];
NSDate *now =[[NSDate alloc]init];
NSLocale *usLocale =[[NSLocale alloc]initWithLocaleIdentifier:#"en_US"];
[dateFormatter1 setLocale:usLocale];
NSString *str_date =[dateFormatter1 stringFromDate:now];
today=[NSString stringWithFormat:#"%#",str_date];
return today;
}
In above code If you print the arryImagePath you can see the image path.Before that you need to allocate and initialize the arryImagePath and array_image.
For Posting data into Server
NSURL *url = [NSURL URLWithString:urlString];
NSString *output = [NSString stringWithContentsOfURL:url encoding:0 error:&error];
NSLog(#"%#",output);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSData *strJsondata=[NSData dataWithBytes:[output UTF8String] length:[output length]];
//If the response is dictionary......
NSDictionary *responseDict = strJsondata ? [NSJSONSerialization JSONObjectWithData:strJsondata options:0 error:&error] : nil;
To upload a file on server you need to make a multipart request which I suggest you to use AFNetworking to do that !
In case you need some multipart example using AFNetworking you can see this or (Upload an image with AFNetworking 2.0) link.
Hope this links could help you.
Update
: To upload Image and Voice on server you need to convert them into data file, his is how you can convert image to data and upload it on server :
NSData *imageData = UIImageJPEGRepresentation(selectedImage, 1.0f);
Then you need to make a request :
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// If you have image you need to do this :
NSString *fileName = #"Some name";
if (imageData) [formData appendPartWithFileData:imageData name:#"photo" fileName:fileName mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Everything is ok
NSLog(#"Success (%d): %#\n\n", (int) operation.response.statusCode, responseObject);
if (success) success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Ops ! we have error
NSLog(#"Failure (%d): %#\n\n", (int) operation.response.statusCode, [error localizedDescription]);
if (failure) failure(nil);
}];
Important : pay attention on mime Type and name , they must be the same name and type requested by server.
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
I have a UIImageview in UICollectionview cell and parse the image data from api and add to UIImageview. Now everything is going perfect but there is some problem I face during scroll down, when I tried to scroll UICollectionview cell its going hang.
Now I need to use NSCache to download image and than add it to UIImage, but I am unable to do this task I am stuck somewhere in my code, I don't know where. Please look at my code.
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
OneTimeCell *cell = (OneTimeCell*)[collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
cell.selected = YES;
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
cell.productname.text = [[productname objectAtIndex:indexPath.row] objectForKey:#"product_name"];
cell.productnumber.text = [[productname objectAtIndex:indexPath.row] objectForKey:#"id"];
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * productimage = [UIImage imageWithData:imageData];
NSURL *absURL = [url absoluteURL];
NSLog(#"absURL = %#", absURL);
if (productimage) {
cell.productimage.image = productimage;
}
else
{
cell.productimage.image = [UIImage imageNamed:#"icon_1.png"];
[self.imageDownloadingQueue addOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImageView *image = nil;
if (image) {
[self.imageCache setObject:image forKey:imageData];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
OneTimeCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
if (cell) {
cell.productimage.image = image;
}
}];
}
}];
}
return cell;
}
in your code line 10 you fetching image on mainthread that is why your cell got stuck . . .Please replace that code with this one
Replace this code
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * productimage = [UIImage imageWithData:imageData];
NSURL *absURL = [url absoluteURL];
NSLog(#"absURL = %#", absURL);
With This one
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
NSData * imageData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage * productimage = [UIImage imageWithData:imageData];
});
});
NSURL *url = #"................";
ImageRequest *request = [[ImageRequest alloc] initWithURL:url];
UIImage *image = [request cachedResult];
if (image) {
// Set the image if exist
} else {
[request startWithCompletion:^(UIImage *image, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if(image) {
cell.productimage.image = productimage;
}else {
// Set any placeholder image here.......
}
});
}];
}
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
//NSData * imageData = [NSData dataWithContentsOfURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if(data)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIImage * productimage = [UIImage imageWithData:data];
});
}
}];
});
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]]];