App crashes with 'NSRangeException' when library is empty - ios

I am using this code to get the latest photo from the cameraRoll:
- (void) getTheLatestPhoto{
ALAssetsLibrary *cameraRoll = [[ALAssetsLibrary alloc] init];
[cameraRoll enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *images, BOOL *stop) {
[images setAssetsFilter:[ALAssetsFilter allPhotos]];
[images enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[images numberOfAssets] - 1] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if (result) {
ALAssetRepresentation *rep = [result defaultRepresentation];
self.sharingImage = [UIImage imageWithCGImage:[rep fullScreenImage]];
}
}];
}
failureBlock: ^(NSError *error) {
NSLog(#"An error occured: %#",error);
}];
}
As it is, if the library cameraRoll is empty, the app will crash with this error:
Terminating app due to uncaught exception 'NSRangeException', reason: 'indexSet count or lastIndex must not exceed -numberOfAssets'
I understand that my indexSet is higher than the numberOfAssets due to this:
[images enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[images numberOfAssets] - 1]
At this point my question is "where do I put a condition that allow me to check if the assets is zero?"
If cameraRoll has more than zero, I will let the code continue, but if the count is zero, I would like to handle the issue this way as oppose to let it crash:
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:#"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
Thanks for your help!

Add if([images numberOfAssets]>0) before enumerateAssetsAtIndexes line and continue code...
or if([images numberOfAssets]<=0) then
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:#"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];

Related

TouchID : How to get touch id authentication attempts?

I need to implement touch ID and have to show alert to user for authentication attempts left. Below code Im using.
reply block not getting called after one wrong authentication attempt. Its getting called after 3 continues wrong authentication attempt. Is there any way to get count of wrong authentication attempts..?
LAContext *myContext = [[LAContext alloc] init];
NSError *authError = nil;
NSString *myLocalizedReasonString = #"Touch ID Test to show Touch ID working in a custom app";
if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
[myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:myLocalizedReasonString
reply:^(BOOL success, NSError *error) {
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:#"Success" sender:nil];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.description
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alertView show];
NSLog(#"Switch to fall back authentication - ie, display a keypad or password entry box");
});
}
}];
} else {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:authError.description
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alertView show];
});
}
I went through the documentation, it is not possible to show alert in each failed attempt. Just refer the documentation
LocalAuthentication in iOS. You can show alerts at different error cases. After 3rd failed attempt LAError.authenticationFailed will be called and after 5th failed attempt LAError.touchIDLockout will be called. You can display the alerts here. For more info refer Apple LAError documentation.

how to Pass recordedFile to collection view cell either by block completion or notification

Hi I have an video recored output and i want to parse it to the other controller using either blocks or nsnotification center. Here is the code used to get output.
- (void)saveRecordedFile:(NSURL *)recordedFile {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary writeVideoAtPathToSavedPhotosAlbum:recordedFile
completionBlock:
^(NSURL *assetURL, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *title;
NSString *message;
if (error != nil) {
title = #"Failed to save video";
message = [error localizedDescription];
}
else {
title = #"Saved!";
message = nil;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
NSLog(#"%#",recordedFile);'
//
}
This output i have to pass to next view controller and from this to time line same like instagram app.
one more thing is already collection view is having images
some body please help me to solve this problem

I am unable to share the url on linked-in through linked-in SDKs which they provide

I am using this code for this sharing . I update my plist with api key and also i have linked-in app on my iPhone.
I am getting success message but url not showing on linked-in page.
- (IBAction)linkedinShare:(id)sender {
NSString *url = #"http://www.tripadvisor.com";
if ([LISDKSessionManager hasValidSession])
{
[[LISDKAPIHelper sharedInstance]postRequest:url body:nil success:^(LISDKAPIResponse *response)
{
if (response)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Linkedin" message:#"Linkedin done" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
NSLog(#"Success is");
} error:^(LISDKAPIError *apiError)
{
NSLog(#"%#",apiError);
}];

Ipad Get Images from custom album Device Issue

Am having a Custom folder in my ipad device. Am using this code to get image from Custom album:
self.assetGroups = [[NSMutableArray alloc] init];
// Group enumerator Block
dispatch_async(dispatch_get_main_queue(), ^
{
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if (group == nil) {
return;
}
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:#"Ganesh"]) {
[self.assetGroups addObject:group];
[self loadImages];
return;
}
if (stop) {
return;
}
};
// Group Enumerator Failure Block
void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
UIAlertView * alert = [[UIAlertView alloc]
initWithTitle:#"ERROR" message:[NSString stringWithFormat:#"No Albums Available"]
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
};
// Enumerate Albums
self.library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:assetGroupEnumberatorFailure];
});
To retrieve all the images from my custom folder I am using this:
(void)loadImages {
ALAssetsGroup *assetGroup = [self.assetGroups objectAtIndex:0];
NSLog(#"asserts group %#",self.assetGroups);
NSLog(#"ALBUM NAME:;%#",[assetGroup valueForProperty:ALAssetsGroupPropertyName]);
[assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop){
if(result == nil) {
return;
}
UIImage *img = [UIImage imageWithCGImage:[[result defaultRepresentation] fullScreenImage]
scale:1.0 orientation:(UIImageOrientation)[[result valueForProperty:#"ALAssetPropertyOrientation"] intValue]];
NSLog(#"image name%#",img);
[arrayOfImage addObject:img];
NSLog(#"arrayOfImage %#",arrayOfImage);
// [imageToAnimate setImage:img];
}];
}
its working fine when i am running with simulator but not in device: it executes Failure block and Says No Album Available.
Its works fine. I have switched Off my location service due to this am not able to access my media now it works fine.

Ipad Application how to get images from custom album

I am developing an iPad application in which I have saved images to custom album using This.
Now I want to get all the images from that custom folder and I need to show all those in a animated UIImageView.
I know how to set animation but I want to know how to get all the images from particular custom folder.
See this code I used to load the images from the custom album. I have used the same sample code to store my images in custom album.
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
self.assetGroups = tempArray;
library = [[ALAssetsLibrary alloc] init];
// Load Albums into assetGroups
// Group enumerator Block
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if (group == nil)
{
return;
}
if([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:kAlbumName])
{
[self.assetGroups addObject:group];
[self reloadTableView];
return;
}
};
// Group Enumerator Failure Block
void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
CustomAlertView * alert = [[CustomAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
NSLog(#"A problem occured %#", [error description]);
};
// Enumerate Albums
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:assetGroupEnumberatorFailure];
Here the kAlbumName is one string ivar which contains the custom album name.
EDIT:1
Above code just gives you the whole album selected with all it photos now to get those photos from album use the following code
[self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if(result == nil)
return;
CGRect viewFrames = kThumbSize;//CGRectMake(0, 0, 75, 75);
UIImageView *assetImageView = [[UIImageView alloc] initWithFrame:viewFrames];
[assetImageView setContentMode:UIViewContentModeScaleToFill];
[assetImageView setImage:[UIImage imageWithCGImage:(__bridge CGImageRef)([result originalAsset])]];
}];
NOTE: Instead of kThumbSize define your CGRectMake() as commented.
Enjoy coding :)
Happy Day :)

Resources