How to get file extension (compare) - ios

i´m parsing the filedirectory from dropbox into a mutablearray, to show it in a table view.
how can i compare the file extension? (.doc, or .jpg,....)
if ([[NSString stringWithFormat:#"%#",[test objectAtIndex:indexPath.row]] isEqualToString:#"??????"] ) {
[cell.extensionView setImage:[UIImage imageNamed:#"word.png"]];
}
isEqualToWhat? is it possible to use wildcards?

Don't use stringWithFormat unless you actually have a format. Your code would be much cleaner if you did something like this:
NSString *filename = [text objectAtIndex:indexPath.row];
NSString *ext = [filename pathExtension];
if ([ext isEqualToString:#"doc"]) {
[cell.extensionView setImage:[UIImage imageNamed:#"word.png"]];
} else if ([ext isEqualToString:#".jpg"]) {
[cell.extensionView setImage:[UIImage imageNamed:#"jpeg.png"]];
}
There is a better way than setting up this big if-else block. I imagine you have lots of different extensions you wish to check. Setup a dictionary with the extensions and images. Something like:
NSDictionary *extensionThumbnails = #{
#"doc" : [UIImage imageNamed:#"word.png"],
#"xls" : [UIImage imageNamed:#"excel.png"],
#"jpg" : [UIImage imageNamed:#"jpeg.png"]
};
Add an entry for each extension and image you have. Then your original code (now using modern Objective-C syntax) becomes:
NSString *filename = text[indexPath.row];
NSString *ext = [filename pathExtension];
UIImage *thumbnail = extensionThumbnails[ext];
if (!thumbnail) {
thumbnail = [UIImage imageNamed:#"unknown.png"];
}
[cell.extensionView setImage:thumbnail];

Related

Convert array of image path into base64 encoded string.?

I want to convert array of Image Paths which are in document directory into Encoded baSE 64 string.
Here is my code
NSArray *recipeImages = [savedImagePath valueForKey:#"Image"];
this array contains path of the images (MULTIPLE IMAGES).
This is how array looks in Logs.
Saved Images == (
"/Users/ZAL02M/Library/Developer/CoreSimulator/Devices/F1F3C01E-8686-4367-82FB-80B003E2F416/data/Containers/Data/Application/694494B1-0DCA-497A-B8B0-586276EEF240/Documents/cached0.png",
"/Users/ZAL02M/Library/Developer/CoreSimulator/Devices/F1F3C01E-8686-4367-82FB-80B003E2F416/data/Containers/Data/Application/694494B1-0DCA-497A-B8B0-586276EEF240/Documents/cached1.png"
)
How to make base64 string ???
Try this to cycle all your images and save each encoded string into a new array:
NSMutableArray *encodedImages = [NSMutableArray new];
for (NSString *path in recipeImages)
{
UIImage *image = [UIImage imageWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *dataString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
[encodedImages addObject:dataString];
}
Convert your ImagePaths (Strings) to NSData and from NSData back to string via base64EncodedStringWithOptions:
Here the code:
NSArray *recipeImages = [savedImagePath valueForKey:#"Image"];
NSMutableArray *mutableBase64StringsArray = #[].mutableCopy;
for (NSString *imagePath in recipeImages)
{
NSData *imagePathData = [imagePath dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64ImagePath = [imagePathData base64EncodedStringWithOptions:0];
[mutableBase64StringsArray addObject:base64ImagePath];
}
In the mutableBase64StringsArray you have all imagePaths as base64 encoded strings.
Look at this post from SO for more explanations: Base64 Decoding in iOS 7+
you can try this
Encoding :
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
Decoding :
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
To get image from your path you can use this code
NSString* imagePath = [recipeImages objectAtIndex:i];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];
Then add encoded content to your array.
Hope it helps.

loop to set UIImages from document directory on viewDidLoad

I have 9 buttons whose images are set by the user dynamically. Each button's current image is saved the user documents folder. In viewDidLoad id like to re-set each image to it's UIButton.
I can do this easily enough with:
NSString *filePath = [self documentsPathForFileName: #"boss1.png"];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[boss1Button setImage:savedBoss forState:UIControlStateNormal];
...... 8 more times....
Of course Id prefer to do it using a loop. Only, Im not sure what that would look like in objective C. In jQuery I could do something like:
$('.bosses').each(function( index ) {
var imageUrl='../images/boss'+(index+1)
$('#'+this.id).css('background-image', 'url(' + imageUrl + ')')
});
How can I create a similar objective-C loop that would increment the boss image name and button name similarly?
Furthermore, is there a better way to do this entirely?
I feel like maybe having an NSArray of image urls and an NSArray of UIButton names and pairing them together using a loop might be better.... but again I'm not sure what the syntax would look like for that here.
Try like this and have button tag like 1 to 8
for (id subview in self.view.subviews) {
if([subview isKindOfClass:[UIButton class]]) {
UIButton* button = (UIButton*)subview;
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFromate#"boss%d.png", button.tag]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[button setImage:savedBoss forState:UIControlStateNormal];
}
}
This will do.
it will be like:
//Add all the buttons in an array for easy loop
NSArray *array = #[btn1,btn2,btn3,btn4... etc];
NSString *name = #"BOSS";
int x = 1;
for(UIButton *btn in array){ // loop through all the buttons
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFormat:#"%#%d.png",name,x]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[btn setImage:savedBoss forState:UIControlStateNormal];
x++;
}

image not showing in UIImage from cached data

I cant possibly get the image that i parsed from the XML to show on my UIImageView using the code below. Am I doing something wrong because I checked it using NSLog to show if there is a link and apparently there is.
NSString *imageURL = [currentData.imageLink];
NSLog(#"this is link = %#", imageURL);
[cachedList addObject:imageURL];
[myCache setObject:cachedList forKey:#"imageURL"];
cachedList = [myCache objectForKey:#"imageURL"]; /where cachedList is NSMutableArray
for(id obj in cachedList){
NSLog(#"value = %#", obj); //to show value
cell.imageShow.image = [UIImage imageNamed:obj];
}
and also I tried doing the below code, but it gives me an error.
if (cachedList != nil) {
cell.imageShow.image = [UIImage imageNamed:[cachedList valueForKey:#"imageURL"]];
}
I think if you are using UITableView then this is the thing i have used and i prefer for tableview
Link: https://github.com/jakemarsh/JMImageCache

MWFeedParser - RSS with images

I have problem, I'm using MWFeedParser Rss reader in my iOS aplication and it works well, but I need to fetch the images from my feed. Can you help me please?
Here is url of that MWFeedParser project: GitHub
I have used this in my cellForRowAtIndexPath function so that it searches for images as the cell is displayed
MWFeedItem *item = itemsToDisplay[indexPath.row];
if (item) {
NSString *htmlContent = item.content;
NSString *imgSrc;
// find match for image
NSRange rangeOfString = NSMakeRange(0, [htmlContent length]);
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"(<img.*?src=\")(.*?)(\".*?>)" options:0 error:nil];
if ([htmlContent length] > 0) {
NSTextCheckingResult *match = [regex firstMatchInString:htmlContent options:0 range:rangeOfString];
if (match != NULL ) {
NSString *imgUrl = [htmlContent substringWithRange:[match rangeAtIndex:2]];
NSLog(#"url: %#", imgUrl);
//NSLog(#"match %#", match);
if ([[imgUrl lowercaseString] rangeOfString:#"feedburner"].location == NSNotFound) {
imgSrc = imgUrl;
}
}
}
}
Note I am also ignoring the image if it has 'feedburner' in the url to avoid feedburner type icons.
I am also using AFNetwork's class when I show the image later
if (imgSrc != nil && [imgSrc length] != 0 ) {
[myimage setImageWithURL:[NSURL URLWithString:imgSrc] placeholderImage:[UIImage imageNamed:IMAGETABLENEWS]];
} else {
NSLog(#"noimage");
cell.imageView.image = [UIImage imageNamed:IMAGETABLENEWS];
//[myimage setImage:[UIImage imageNamed:IMAGETABLENEWS]];
}
I have left in my commented NSLog parts so you can uncomment and check if you want
Make sure you have an IMAGETABLENEWS constant for the placeholder or get rid of that part as you need.
This is only a very simple check of images in the html text and is not comprehensive. It served my purpose and may help you get your logic right for doing something more detailed.
In case your MWFeedItem has an image embedded in it's enclosure-tag, you might want to consider to do the following:
MWFeedItem has a property called enclosures. It's an array containing one or more dictionaries.
This dictionaries are generated in
- (BOOL)createEnclosureFromAttributes:(NSDictionary *)attributes andAddToItem:(MWFeedItem *)currentItem (MWFeedParser.M).
These dictionaries have three keys (if available): url, type & length.
That first one is probably the one you're looking for. I managed to get it like this:
Feed Example
<item>
<title>Item title</title>
<link>http://www.yourdomain.com</link>
<description>Item description</description>
<pubDate>Mon, 01 Jan 2016 12:00:00 +0000</pubDate>
<enclosure url="http://www.yourdomain.com/image.jpg" length="0" type="image/jpeg"></enclosure>
<category>Algemeen</category>
</item>
Please notice the image link inside <enclosure></enclosure>
YourViewController.m
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSArray *EnclosureArray = item.enclosures;
NSDictionary *ImageDict = [EnclosureArray objectAtIndex:0]; // 0 Should be replaced with the index of your image dictionary.
NSString *ImageLink = [ImageDict objectForKey:#"url"];
// Returns: http://www.yourdomain.com/image.jpg
}

iOS Split view controller - changing image in detailViewController

This is another of those "I'm sure there's an easy answer to this" questions, but I find myself baffled.
I'm using the split view controller from the template. I'm successfully passing a NSString to the _detailItem variable, but am unable to use it to create and load an image into an UIImageView (named "stripImage").
It works up until:
[self.stripImage setImage:[UIImage imageNamed: _detailItem]];
If I put a string literal into the same line of code (like #"image20.jpg"), it works fine.
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
NSLog(#"_detailItem is still: %#",_detailItem);
// correctly reports the name of the imagefile (for example: "image20.jpg"
[self.stripImage setImage:[UIImage imageNamed: _detailItem]];
NSLog(#"The image being shown is: %#",self.stripImage.image);
//returns "The image being shown is: (null)"
}
}
Please help keep my head from exploding. Thanks in advance.
... and I've tried it this way:
(in my Master view controller):
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Selected row %i",[indexPath row]);
NSString *imageName = [[stories objectAtIndex:[indexPath row]] objectForKey:#"link"];
NSLog(#"The image is: %#", imageName);
// These two work, oddly enough...
self.detailViewController.detailTitle.text = [[stories objectAtIndex:[indexPath row]]
objectForKey:#"title"];
self.detailViewController.detailSubtitle.text = [[stories objectAtIndex:[indexPath row]]
objectForKey:#"subtitle"];
// this one, not so much...
[self.detailViewController loadUpImageWith:imageName];
}
and in my Detail view controller:
- (void)loadUpImageWith:(NSString *)what
{
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[NSString
stringWithFormat:#"strips/%#", what]];
NSLog(#"The file's url is: %#",path);
UIImage *img = [UIImage imageWithContentsOfFile:path];
NSLog(#"The resultant image is: %#",img);
stripImage.image = img;
}
But here's the weird thing... If I replace the variable ("what" in this case) with a string literal:
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[NSString
stringWithFormat:#"strips/%#", #"grumbles300.jpg"]];
... it works, displaying that one image. But I want to be able to use a variable there!!
Help me Obiwan Kenobi! You're my only hope.
Embarrassing operator error.
I was adding a buncha images to the bundle, but it apparently kept track of the folder that contained them, which needed to be added to the file name. I thought UIImage imageNamed: would track down the images, as long as they were contained in the main bundle. Apparently not.
Perhaps this would be useful to someone who's experiencing the same sort of brain fart.
After resolving this, it was easy to do this:
- (void)loadupDetailTitle:(NSString *)title
subtitle:(NSString *)subtitle
image:(NSString *)imageName
{
NSString *path = [#"strips/" stringByAppendingPathComponent:imageName];
stripImage.image = [UIImage imageNamed:path];
detailTitle.text = title;
detailSubtitle.text = subtitle;
}

Resources