top of page

IOS Programming: Loading image from iPhone library and displaying it on the device screen.

Step1: Adding necessary libraries like image below.

Step2: click on ViewController.m to open your code window and then put the following code inside method "viewdidload".

PHFetchResult *colResult = [PHAssetCollection fetchMomentsWithOptions:nil];

if(colResult != nil){

if([colResult count] > 0)

m_PHAssetColObj = [colResult objectAtIndex:0];

}

PHFetchResult *assetResult = [PHAsset fetchAssetsInAssetCollection:m_PHAssetColObj options:nil];

if(assetResult != nil){

if([assetResult count] > 0){

NSLog(@"%i",[assetResult count]);

m_PHAssetObj = [assetResult objectAtIndex:0];

}

}//End assetResult != nil

i

CGSize imgSize;

imgSize.width = 50.0f;

imgSize.height = 100.0f;

[[PHImageManager defaultManager] requestImageForAsset:m_PHAssetObj targetSize:imgSize contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage *ret,NSDictionary *info){

CGPoint imgPos = CGPointMake(100.0f,200.0f);

UIImageView *imgView = [[UIImageView alloc] initWithImage:ret];

[imgView setCenter:imgPos];

[self.view addSubview:imgView];

}];

Let’s see how the code above work

First, The instance of class PHAssetCollection is created. This object is used to fetch photos from collections of your photo library on the device. The we use method “fetchMomentsWithOptions” which is one of method that can be used to fetch collections of photo on the device. Then the instance object of class PHAsset is created in order to fetch photo assets from each collection. In this tutorial we will only fetch photo from the first collection. For now, we will have photo assets fetching from the collection. It is time to display it on the screen. To display it on the screen, the photo assets information need to be converted to UIImage so that it can be added to the view or shown on the screen. To do that, use requestImageForAsset, one of method to convert photo asset into UIImage of class PHImageManager. This method contain 4 parameters including

- PHAsset (The asset object that you want to convert it to UIImage)

- targetSize (the size of image displayed on the screen)

- contentMode (mode to display image)

- option

- the resultHandler block that will be execute after the assets converted into UIImage

It contain two parameters which allow you to edit the image. Now inside the block, UIImageView object was created. then the UIImage in the first parameter is added to this view. Finally, add this image view to the controller view again. Run and build your code to see the result.

bottom of page