raymondis
raymondis

Reputation: 356

How to Load an Image from URL in Xamarin.iOS

When I pick a picture from Gallery I have something like this:

NSUrl referenceURL = e.Info[new  
NSString("UIImagePickerControllerReferenceURL")] as NSUrl;
//imageURL = referenceURL.AbsoluteString;
imageURL = referenceURL.AbsoluteUrl.ToString();
string path = referenceURL.Path;

NSUrl url1 = referenceURL.FilePathUrl;
NSUrl url2 = referenceURL.FileReferenceUrl;

Now I'm trying to load that Image from the URL:

var url = new NSUrl(imageURL);
var data = NSData.FromUrl(url);
defectImage.Image = UIImage.LoadFromData(data);

But data is still null.

What is the correct way to load an Image from URL?

Note: url1 and url2 are just examples. path is something like = "/imagename.jpg"

Maybe I'm retrieving the URL on a wrong way? there are so many methods to get a path/url.

Upvotes: 0

Views: 2412

Answers (2)

Benoit Canonne
Benoit Canonne

Reputation: 455

You can use the nuget package FFImageLoading :

ImageService.Instance.LoadUrl("url").Into(YourUIImageView);

Upvotes: 0

SushiHangover
SushiHangover

Reputation: 74094

Since these image urls are "assets-library" based, so you need to go through the ALAssetsLibrary to access them:

var url = e.Info[UIImagePickerController.ReferenceUrl] as NSUrl;
var asset = new ALAssetsLibrary();
UIImage image;
asset.AssetForUrl(
    url, 
    (ALAsset obj) =>
    {
        var assetRep = obj.DefaultRepresentation;
        var cGImage = assetRep.GetFullScreenImage();
        image = new UIImage(cGImage);
        // Do something with "image" here... i.e.: assign it to a UIImageView
        imageView.Image = image;
    }, 
    (NSError err) => 
    { 
        Console.WriteLine(err);
    }
);

Note: You really should start using the Photos framework if you do not have to support iOS 7 clients....

The Assets Library framework is deprecated as of iOS 9.0. Instead, use the Photos framework instead, which in iOS 8.0 and later provides more features and better performance for working with a user’s photo library.

Ref: https://developer.apple.com/library/ios/documentation/AssetsLibrary/Reference/ALAssetsLibrary_Class/index.html

Upvotes: 3

Related Questions