Paweł Brewczynski
Paweł Brewczynski

Reputation: 2743

How to load image to UIImage from file without extension

I have a resources downloaded at the runtime. Images reside in some sub folder in the "caches" directory.

How can I load image to UIImage when I know the path to the file, image is "PNG" type, but it doesn't have extension?

I could not see any constructor of UIImage which takes type of the file as argument, so I reckon that it could be tricky one

Upvotes: 0

Views: 1330

Answers (2)

Just a coder
Just a coder

Reputation: 16730

Since your file is already downloaded

let path = "theFilePath"
if let data = NSData(contentsOfFile: path)  {
    let image = UIImage(data: data as Data)
}

Upvotes: 1

rckoenes
rckoenes

Reputation: 69499

No this is not that hard, just load the data first. Here the cacheURL is a NSURL to the file.

NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:cacheURL options:NSDataReadingMapped error:&error];

Now you can check if the file could be loaded:

if (data) {
    image = [UIImage imageWithData:data];
}

Code is in Objective-C because I just copied from an old project, but should easy to convert to Swift.

Upvotes: 0

Related Questions