Load image from bundle with iOS - ios

I added to my project a .bundle folder filled with some images.
Is it correct refer to this image directly writing something like ?:
[UIImage imageNamed:#"imageInBundle.png"];
Which is the best method to access and use these images ?

That is correct, imageNamed: will search your main bundle. Images in your project, even if they are in different groups in your Project Navigator will be in your main bundle and can be accessed directly by name.

If that does not work, try
[UIImage imageNamed:#"yourbundlefile.bundle/imageInBundle.png"];
Best

Apple has thankfully provided a proper API for this from iOS 8 onwards, imageNamed:inBundle:compatibleWithTraitCollection:.
It's used like so:
[UIImage imageNamed:#"image-name"
inBundle:[NSBundle bundleForClass:self.class]
compatibleWithTraitCollection:nil]
or in swift:
let image = UIImage(named: "image-name",
inBundle: NSBundle(forClass: type(of:self)),
compatibleWithTraitCollection: nil)
or in swift 5:
let image = UIImage(named: "image-name",
in: Bundle(for: type(of:self)),
compatibleWith: nil)

1) If you are working with bundles go to bundle target and set COMBINE_HIDPI_IMAGES to NO.
In another case the image will be converted to tiff format.
2) try this code:
NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:#"YourBundle" withExtension:#"bundle"]];
NSString *imagePath = [bundle pathForResource:#"imageInBundle" ofType:#"png"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

Swift 3
let myImage = UIImage(named: "nameOfImage", in: Bundle(for: type(of: self)), compatibleWith: nil)
I can't get current bundle so i do this:
Bundle(for: type(of: self))

This Method returns image anywhere in the xcode project:=>
+(UIImage*)returnImageFromResourceBundle:(NSString*)nameOfImage
{
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"Resource" ofType:#"bundle"];
NSString *imageString = [[NSBundle bundleWithPath:bundlePath] pathForResource:nameOfImage ofType:#"png"];
UIImage *retrievedImage = [[UIImage alloc] initWithContentsOfFile: imageString];
return retrievedImage;
}

Swift version
#AndrewMackenzie's answer didn't work me. This is what did work
let image = UIImage(named: "imageInBundle.png")
imageView.image = image
My full answer is here.

Since I had to figure this out for Swift, thought I would add also....
if let imagePath = NSBundle.mainBundle().pathForImageResource("TestImage.png")
{
imageView.image = NSImage(contentsOfFile: imagePath)
}
Where I have TestImage.png in the Supporting Files group inside my bundle.

For Swift 3
let prettyImage = UIImage(named: "prettyImage",
in: Bundle(for: self),
compatibleWith: nil)

A quick way to do it if you are going to use it a couple of times in the same viewController:
Get the image anywhere in the same class as the method below:
// this fetches the image from: MyBundle.bundle/folder/to/images/myImage.png
UIImage *myImage = [self imageFromBundle:#"MyBundle" withPath:#"folder/to/images/myImage.png"];
Method that fetches the image:
- (UIImage *)imageFromBundle:(NSString *)bundleName withPath:(NSString *)imageName
{
NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:bundleName withExtension:#"bundle"];
NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
NSString *imagePath = [bundle pathForResource:imageName ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
return image;
}
Or simply call it straight out of the bundle:
UIImage *myImage = [UIImage imageNamed:#"MyBundle.bundle/folder/to/images/myImage.png"];

If you are building a framework and you would like all instances of UIImage(named: "image") to always use your custom bundle, you can make an extension like below that will override it
// Swift 5
extension UIImage {
convenience init?(named: String) {
self.init(named: named, in: <#Your Bundle#>, compatibleWith: nil)
}
}

This is worked for me in Swift 5
// Empty UIImage array to store the images in it.
var icons = [UIImage]()
let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("MyBundle.bundle") // Bundle URL
do {
let contents = try fileManager.contentsOfDirectory(at: assetURL,
includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey],
options: .skipsHiddenFiles)
for item in contents { // item is the URL of everything in MyBundle imgs or otherwise.
let image = UIImage(contentsOfFile: item.path) // Initializing an image
icons.append(image!) // Adding the image to the icons array
}
}
catch let error as NSError {
print(error)
}

I found this question when trying to solve loading images from Swift Package, so if anybode else is struggling with that as well here's how I solved it:
let image = UIImage(named: "imageName", in: Bundle.module, compatibleWith: nil)

Related

Retrieving image from asset folder - iOS

I'm writing a class to build a cocoapods and I want to get the image I placed in Assets.xcassets. The problem is always getting nil image. Are there anything I miss?
Here is my podspec file :
Here is the directory stucture :
This is what I try to load the Image:
#import "HaloImage.h"
#implementation HaloImage
- (void)showImage {
NSBundle * bundle = [NSBundle bundleForClass:self];
NSURL * bundleUrl = [bundle URLForResource:#"Assets" withExtension:#"bundle"];
self.image = [UIImage imageNamed:bundleUrl.absoluteString];
}
#end
You can access image from Assets.xcassets by this. Give it a try
UIImage *image = [UIImage imageNamed:#"image name without extension"];
you can use image from asset or main bundle only by name (png file)
self.image = [UIImage imageNamed:#"name_of_image"];
Can you please try below code :
#implementation HaloImage
- (void)showImage {
NSBundle * bundle = [NSBundle bundleForClass:self];
NSURL * bundleUrl = [bundle pathForResource:#"Assets" withExtension:#"bundle"];
self.image = [UIImage imageNamed:bundleUrl.absoluteString];
}
#end

Copy video from Resource to UIPasteboard

I am Developing a custom keyboard with Keyboard Extension.
I want to copy video from my resource folder to UIPasteboard. For that i am using below code but no luck
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:#"SampleVideo_1280x720_1mb" ofType:#"mp4"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
NSData *data = [NSData dataWithContentsOfURL:movieURL];
[[UIPasteboard generalPasteboard]setPersistent:YES];
[[UIPasteboard generalPasteboard] setData:data forPasteboardType:(NSString *)kUTTypeVideo];
Can you please help me this?
And one more thing is it Possible to do?
Thanks in advance.
The pasteboardType you are using (kUTTypeVideo) is for a type of movie that has no sound. This will not work. If you copied an mp4 file to the pasteboard using that pasteboardType, and then say, pasted it into an iMessage chat field, it'll show that it's an unknown and unplayable format.
Instead, use kUTTypeQuickTimeMovie or kUTTypeMPEG4. This will work.
Also, no need to setPersistent to Yes; this is the general pasteboard which is a system pasteboard that transcends the space-time of any app, and so you don't need to do that. :)
Try this code. It worked for me.
let pb = UIPasteboard.generalPasteboard()
let url: NSURL = NSBundle.mainBundle().URLForResource("\(tempArray[indexPath.row])", withExtension: "mp4")!
let data1: NSData = try! NSData(contentsOfURL: url, options: NSDataReadingOptions.DataReadingMappedIfSafe)
let data: NSData = NSData(contentsOfURL: url)!
print(data)
pb.persistent = true
pb.setData(data1, forPasteboardType: "public.mpeg-4")
And also if u want to get the URL of the video from the NSBundle you need to add the video locally.

Accessing images from nsbundle

I have a framework which is trying to access xib's and images from a bundle. I am able to access the xib fine but unable to load the images in UIImageView. I even check if the file exists and the console output is yes...
Any idea how to load the image?
Code to load xib in the framework viewcontroller file
self = [super initWithNibName:#"ViewController_iPad" bundle:[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:#"MyBundle" ofType:#"bundle"]]];
Code to load images
- (void) loadImage
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"MyBundle.bundle/test" ofType:#"png"];
BOOL present = NO;
present = [[NSFileManager defaultManager] fileExistsAtPath:path];
if (present)
{
NSLog(#"MyBundle.bundle/test exists");
}
else
{
NSLog(#"MyBundle.bundle/test does not exists");
}
self.testImageView.image = [UIImage imageNamed:path];
self.testImageView2.image = [UIImage imageWithContentsOfFile:path];
}
MyTestHarnessApp[11671:c07] MyBundle.bundle/test exists
When you use imageNamed: you must pass just a simple filename and the image must exist in the root of the app's resource bundle.
Your image is not in the root of the resource bundle, it is in a subfolder.
Since you have obtained the image's full path in the path variable, you must use the UIImage imageWithContentsOfFile: method:
self.testImageView.image = [UIImage imageWithContentsOfFile:path];
If +[UIImage imageNamed:] isn't resolving the path correctly, you could always use:
self.testImageView.image = [UIImage imageWithContentsOfFile: path];
You can just use the following:
self.testImageView.image = [UIImage imageNamed:#"MyBundle.bundle/test.png"];
But it seems that if you put the XIB in the bundle too, the interface will be relative to the bundle.
self.testImageView.image = [UIImage imageNamed:#"test.png"]
try going step by step.
First get the path to the bundle within your main bundle:
NSString *myBundlePath=[[NSBundle mainBundle] pathForResource:MyBundle ofType:#"bundle"];
Check to see if there is anything in the bundle. This is more for double checking. Once it is working you can choose to omit this code. But it is always a good idea to double check things.
NSBundle *imageBundle=[NSBundle bundleWithPath: myBundlePath];
NSArray *allImageURLs=[imageBundle URLsForResourcesWithExtension:#"png" subdirectory:nil];
NSLog(#"imageURLS: %#",allImageURLS);
Since you already have the bundle path add the image name to the path. Or you can just pull it from the list of urls that you already have in the above code.
NSString *myImagePath=[myBundlePath stringByAppendingPathComponent:#"test.png"];
NSLog(#"myImagePath=%#",myImagePath);
Then, since you have the full path, load the image
UIImage *testImage = [UIImage imageWithContentsOfFile:backgroundImagePath];
Code taken from shipping app.
Good Luck
Tim
If the images are already in the main bundle just use the image name: test.png or simply test
[UIImage imageNamed:#"test.png"];
[UIImage imageNamed:#"test"];

How can i get the name of image picked through photo library in iphone?

I am picking an image from photo library in iphone application. How will i retrieve the actual image name.
in .h class
UIImageView * imageView;
UIButton * choosePhotoBtn;
in .m class
-(IBAction) getPhoto:(id) sender
{
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if((UIButton *) sender == choosePhotoBtn)
{
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
else
{
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
imageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
}
How will i get the actual name of image ?
I m new in iphone. Please help me.
Thanks in advance.
import AssetsLibrary in your file:
#import <AssetsLibrary/AssetsLibrary.h>
And, in - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
put
// get the ref url
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSLog(#"[imageRep filename] : %#", [imageRep filename]);
};
// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
so you'll get the image name in log.
*don't forget to add existing framework: AssetsLibrary.framework
Steps:
In the project navigator, select your project
Select your target
Select the 'Build Phases' tab
Open 'Link Binaries With Libraries' expander
Click the '+' button
Select your framework
(optional) Drag and drop the added framework to the 'Frameworks' group
Source:
http://www.raywenderlich.com/forums/viewtopic.php?f=2&p=34901
&
How to "add existing frameworks" in Xcode 4?
If you are building for iOS 9+ target, you will see a bunch of deprecation warnings with ALAssetsLibrary, i.e.:
'assetForURL(_:resultBlock:failureBlock:)' was deprecated in iOS 9.0: Use fetchAssetsWithLocalIdentifiers:options: on PHAsset to fetch assets by local identifier (or to lookup PHAssets by a previously known ALAssetPropertyAssetURL use fetchAssetsWithALAssetURLs:options:) from the Photos framework instead
As the warning describes, you should use PHAsset. Using swift 2.x, for example, you will need to add import Photos to your file first. Then, in the didFinishPickingMediaWithInfo UIImagePickerControllerDelegate method use fetchAssetsWithALAssetURLs to get the filename:
if let imageURL = info[UIImagePickerControllerReferenceURL] as? NSURL {
let result = PHAsset.fetchAssetsWithALAssetURLs([imageURL], options: nil)
let filename = result.firstObject?.filename ?? ""
}
This will set filename to be something like, "IMG_0007.JPG".
Simple Swift implementation:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL {
ALAssetsLibrary().assetForURL(referenceUrl, resultBlock: { asset in
let fileName = asset.defaultRepresentation().filename()
//do whatever with your file name
}, failureBlock: nil)
}
}
}
Remember about: import AssetsLibrary
In Objective C, use the Photos framework and import Photos/Photos.h
Then, in your imagePickerController function
add the following to get the filename of the image from the photo library
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
NSString *filename = [[result firstObject] filename];
Though you may be able to retrieve the last path component and use it like a file name, it is not advisable to do so. These filenames are assigned by the system for iTunes to understand while syncing and are not meant for programmers to access as they could be replaced by some other images in future syncs.
A good round about for this is to assign the current Date as filenames, while saving to images picked from the gallery. You may save it in your documents or library directory and use a mapping PList file to map images to their filename.
Alternatively, you can also assign unique numbers as filenames and access the images using these values.
Objective C implementation that works on iOS 10. ALAssetsLibrary seems to be deprecated so you should use PHAsset:
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHAsset *phAsset = [[PHAsset fetchAssetsWithALAssetURLs:#[imageURL] options:nil] lastObject];
NSString *imageName = [phAsset valueForKey:#"filename"];
UIImage *photo = [info valueForKey:UIImagePickerControllerOriginalImage];
NSLog(#"Picked image: %# width: %f x height: %f",imageName, photo.size.width, photo.size.height);
[picker dismissViewControllerAnimated:YES completion:nil];
}
As of Swift 3 and iOS8+ the .filename is not accessible any more. It is still available through self.valueForKey("filename"), but not quite legal though.
However, I found this answer in the question "iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?" to be short, simple, and legal.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
self.dismiss(animated: true, completion: nil);
}
var fileName: String = "Attachment"
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let assets = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
let assetResource = PHAssetResource.assetResources(for: assets.firstObject!)
fileName = assetResource.first?.originalFilename ?? "Attachment"
}
print(fileName)

Can I load a UIImage from a URL?

I have a URL for an image (got it from UIImagePickerController) but I no longer have the image in memory (the URL was saved from a previous run of the app). Can I reload the UIImage from the URL again?
I see that UIImage has a imageWithContentsOfFile: but I have a URL. Can I use NSData's dataWithContentsOfURL: to read the URL?
EDIT1
based on #Daniel's answer I tried the following code but it doesn't work...
NSLog(#"%s %#", __PRETTY_FUNCTION__, photoURL);
if (photoURL) {
NSURL* aURL = [NSURL URLWithString:photoURL];
NSData* data = [[NSData alloc] initWithContentsOfURL:aURL];
self.photoImage = [UIImage imageWithData:data];
[data release];
}
When I ran it the console shows:
-[PhotoBox willMoveToWindow:] file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG
*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0'
Looking at the call stack, I'm calling URLWithString, which calls URLWithString:relativeToURL:, then initWithString:relativeToURL:, then _CFStringIsLegalURLString, then CFStringGetLength, then forwarding_prep_0, then forwarding, then -[NSObject doesNotRecognizeSelector].
Any ideas why my NSString (photoURL's address is 0x536fbe0) doesn't respond to length? Why does it say it doesn't respond to -[NSURL length]? Doesn't it know that param is an NSString, not a NSURL?
EDIT2
OK, the only problem with the code is the string to URL conversion. If I hardcode the string, everything else works fine. So something is wrong with my NSString and if I can't figure it out, I guess that should go in as a different question. With this line inserted (I pasted the path from the console log above), it works fine:
photoURL = #"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG";
You can do it this way (synchronously, but compact):
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];
A much better approach is to use Apple's LazyTableImages to preserve interactivity.
You can try SDWebImage, it provides:
Asynchronous loading
Caching for offline use
Place holder image to appear while loading
Works well with UITableView
Quick example:
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
And the swift version :
let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData)
If you're really, absolutely positively sure that the NSURL is a file url, i.e. [url isFileURL] is guaranteed to return true in your case, then you can simply use:
[UIImage imageWithContentsOfFile:url.path]
get DLImageLoader and try folowing code
[DLImageLoader loadImageFromURL:imageURL
completed:^(NSError *error, NSData *imgData) {
imageView.image = [UIImage imageWithData:imgData];
[imageView setContentMode:UIViewContentModeCenter];
}];
Another typical real-world example of using DLImageLoader, which may help someone...
PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
#"http://graph.facebook.com/%#/picture?type=large",
[aFacebookUser objectForKey:#"id"] ];
__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
completed:^(NSError *error, NSData *imgData)
{
if ( loadMe == nil ) return;
if (error == nil)
{
UIImage *image = [UIImage imageWithData:imgData];
image = [image ourImageScaler];
loadMe.image = image;
}
else
{
// an error when loading the image from the net
}
}];
As I mention above another great library to consider these days is Haneke (unfortunately it's not as lightweight).
Try this code, you can set loading image with it, so the users knows that your app is loading an image from url:
UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"loading.png"]];
[yourImageView setContentMode:UIViewContentModeScaleAspectFit];
//Request image data from the URL:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://yourdomain.com/yourimg.png"]];
dispatch_async(dispatch_get_main_queue(), ^{
if (imgData)
{
//Load the data into an UIImage:
UIImage *image = [UIImage imageWithData:imgData];
//Check if your image loaded successfully:
if (image)
{
yourImageView.image = image;
}
else
{
//Failed to load the data into an UIImage:
yourImageView.image = [UIImage imageNamed:#"no-data-image.png"];
}
}
else
{
//Failed to get the image data:
yourImageView.image = [UIImage imageNamed:#"no-data-image.png"];
}
});
});
Check out the AsyncImageView provided over here. Some good example code, and might even be usable right "out of the box" for you.
AFNetworking provides async image loading into a UIImageView with placeholder support. It also supports async networking for working with APIs in general.
Make sure enable this settings from iOS 9:
App Transport Security Settings in Info.plist to ensure loading image from URL so that it will allow download image and set it.
And write this code:
NSURL *url = [[NSURL alloc]initWithString:#"http://feelgrafix.com/data/images/images-1.jpg"];
NSData *data =[NSData dataWithContentsOfURL:url];
quickViewImage.image = [UIImage imageWithData:data];
The way using a Swift Extension to UIImageView (source code here):
Creating Computed Property for Associated UIActivityIndicatorView
import Foundation
import UIKit
import ObjectiveC
private var activityIndicatorAssociationKey: UInt8 = 0
extension UIImageView {
//Associated Object as Computed Property
var activityIndicator: UIActivityIndicatorView! {
get {
return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView
}
set(newValue) {
objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
private func ensureActivityIndicatorIsAnimating() {
if (self.activityIndicator == nil) {
self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.activityIndicator.hidesWhenStopped = true
let size = self.frame.size;
self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2);
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.addSubview(self.activityIndicator)
self.activityIndicator.startAnimating()
})
}
}
Custom Initializer and Setter
convenience init(URL: NSURL, errorImage: UIImage? = nil) {
self.init()
self.setImageFromURL(URL)
}
func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) {
self.ensureActivityIndicatorIsAnimating()
let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
if (error == nil) {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.activityIndicator.stopAnimating()
self.image = UIImage(data: data)
})
}
else {
self.image = errorImage
}
}
downloadTask.resume()
}
}
The Best and easy way to load Image via Url is by this Code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
imgView.image= [UIImage imageWithData:data];
});
});
Replace imgUrl by your ImageURL
Replace imgView by your UIImageView.
It will load the Image in another Thread, so It will not slow down your App load.
Local URL's are super simple, just use this :
UIImage(contentsOfFile: url.path)

Resources