Check ALAssetsLibrary empty or not - iphone

I am using ALAssetsLibrary and app getting crashed when it is empty.How do i check whether it is empty or not?.
-(void)getLastImageName1
{
// if (val < 10) {
// NSLog(#"getLastImageName1\n");
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
last =1;
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just photos.
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
if (last == 1) {
// NSLog(#"last\n");
last++;
// Chooses the photo at the last index
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[group numberOfAssets]-1] options:0 usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
NSString *lastImgNew = alAsset.defaultRepresentation.filename;
// NSLog(#"current img name %#\n",lastImgNew);
NSString *plistPath1 = [DOCUMENT_DIR_PATH stringByAppendingPathComponent:#"previouslastimagename.plist"];
NSArray *lastImg = [NSArray arrayWithContentsOfFile:plistPath1];
// NSLog(#"get pre lastimg %#\n",lastImg);
// NSArray *lastImg = [[DBModel database]getPreviousName];
// NSLog(#"get lastImg %#\n",lastImg);
if ([lastImg count] != 0) {
// NSLog(#"count\n");
if ([[lastImg objectAtIndex:0] isEqualToString:lastImgNew]) {
// NSLog(#"img eql\n");
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:#"equal" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
[self hideImage];
// }
}
else
{
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:[NSString stringWithFormat:#"pre %# current %#",[lastImg objectAtIndex:0],lastImgNew] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
// NSLog(#"img not eql\n");
[self performSelectorOnMainThread:#selector(displayAlert) withObject:nil waitUntilDone:YES];
}
}
}
}];
}
} failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
// NSLog(#"No groups");
}];
The line which after last++ variable.I am checking lastimage with newscreenshot image to not allow user to use app after taking screenshot

This is the line that is giving you the error:
[NSIndexSet indexSetWithIndex:[group numberOfAssets]-1]
If there are zero assets then you are setting the index to -1. You can wrap that enum block in a conditional to test if numberOfAssets > 0 before proceeding. Also, there are other questions you may find helpful to look at here. Ex.: How to get the latest photo in iPhone Library?

Related

Not able to access Contacts in iOS7

I am using the following code to get the contacts from the User's Phone
CFErrorRef error;
__block BOOL accessGranted;
ABAddressBookRef myAddressBook = ABAddressBookCreateWithOptions(NULL,&error);
ABAddressBookRequestAccessWithCompletion(myAddressBook, ^(bool granted, CFErrorRef error)
{
if (!accessGranted && !granted)
{
alertViewDeny = [[UIAlertView alloc]initWithTitle:#"Deny Access" message:#"Deny" delegate:self cancelButtonTitle:nil otherButtonTitles:#"cancel", nil];
[alertViewDeny show];
[alertViewDeny release];
}
else
{
NSArray *allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
DLog(#"allPeople %#",allPeople);
}
In Output I am getting //Only for iOS7 and it is working iOS6.
allPeople( )

Changeing anypic from photo to video

I have used Anypic open source to save a photo taken with the app to an in-app feed. I would like to convert it to save videos instead of photos. How would I go about doing this. Here is the code that i am using to save the photo-
- (BOOL)shouldUploadImage:(UIImage *)anImage {
// Resize the image to be square (what is shown in the preview)
UIImage *resizedImage = [anImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit
bounds:CGSizeMake(560.0f, 560.0f)
interpolationQuality:kCGInterpolationHigh];
// Create a thumbnail and add a corner radius for use in table views
UIImage *thumbnailImage = [anImage thumbnailImage:86.0f
transparentBorder:0.0f
cornerRadius:10.0f
interpolationQuality:kCGInterpolationDefault];
// Get an NSData representation of our images. We use JPEG for the larger image
// for better compression and PNG for the thumbnail to keep the corner radius transparency
NSData *imageData = UIImageJPEGRepresentation(resizedImage, 0.8f);
NSData *thumbnailImageData = UIImageJPEGRepresentation(thumbnailImage, 0.8f);
if (!imageData || !thumbnailImageData) {
return NO;
}
// Create the PFFiles and store them in properties since we'll need them later
self.photoFile = [PFFile fileWithData:imageData];
self.thumbnailFile = [PFFile fileWithData:thumbnailImageData];
// Save the files
[self.photoFile saveInBackground];
[self.thumbnailFile saveInBackground];
}
- (void)doneButtonAction:(id)sender {
NSDictionary *userInfo = [NSDictionary dictionary];
NSString *trimmedComment = [self.commentTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (trimmedComment.length != 0) {
userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
trimmedComment,kPAPEditPhotoViewControllerUserInfoCommentKey,
nil];
}
if (!self.photoFile || !self.thumbnailFile) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Couldn't post your photo" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
return;
}
// both files have finished uploading
// create a photo object
PFObject *photo = [PFObject objectWithClassName:kPAPPhotoClassKey];
[photo setObject:[PFUser currentUser] forKey:kPAPPhotoUserKey];
[photo setObject:self.photoFile forKey:kPAPPhotoPictureKey];
[photo setObject:self.thumbnailFile forKey:kPAPPhotoThumbnailKey];
// photos are public, but may only be modified by the user who uploaded them
PFACL *photoACL = [PFACL ACLWithUser:[PFUser currentUser]];
[photoACL setPublicReadAccess:YES];
photo.ACL = photoACL;
// Request a background execution task to allow us to finish uploading the photo even if the app is backgrounded
self.photoPostBackgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:self.photoPostBackgroundTaskId];
}];
// save
[photo saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded) {
NSLog(#"Photo uploaded");
[[PAPCache sharedCache] setAttributesForPhoto:photo likers:[NSArray array] commenters:[NSArray array] likedByCurrentUser:NO];
// userInfo might contain any caption which might have been posted by the uploader
if (userInfo) {
NSString *commentText = [userInfo objectForKey:kPAPEditPhotoViewControllerUserInfoCommentKey];
if (commentText && commentText.length != 0) {
// create and save photo caption
PFObject *comment = [PFObject objectWithClassName:kPAPActivityClassKey];
[comment setObject:kPAPActivityTypeComment forKey:kPAPActivityTypeKey];
[comment setObject:photo forKey:kPAPActivityPhotoKey];
[comment setObject:[PFUser currentUser] forKey:kPAPActivityFromUserKey];
[comment setObject:[PFUser currentUser] forKey:kPAPActivityToUserKey];
[comment setObject:commentText forKey:kPAPActivityContentKey];
PFACL *ACL = [PFACL ACLWithUser:[PFUser currentUser]];
[ACL setPublicReadAccess:YES];
comment.ACL = ACL;
[comment saveEventually];
[[PAPCache sharedCache] incrementCommentCountForPhoto:photo];
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:PAPTabBarControllerDidFinishEditingPhotoNotification object:photo];
} else {
NSLog(#"Photo failed to save: %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Couldn't post your photo" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
}
[[UIApplication sharedApplication] endBackgroundTask:self.photoPostBackgroundTaskId];
}];
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
PFFile *videoFile = [PFFile fileWithData:videoData];
[self.videoFile saveInBackground];
You would treat the video as any other file in parse. I would look into Apples documentation for video on handling video files on iOS.

Multiple objects in PFQueryTableViewController - Parse.com

I'm trying to display two objects or "classNames" into a PFQueryTableViewController. Here is my code so far with only one object. I can't seem to be able to add more than one object.
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// Customize the table
// The className to query on
self.className = #"Funny";
//self.className = #"Story";
// The key of the PFObject to display in the label of the default cell style
self.textKey = #"title";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = YES;
// The number of objects to show per page
self.objectsPerPage = 100;
}
return self;
}
Just add more #propertys to your view controller. Make sure to add the necessary ones (className2, textKey2, etc) and to modify the datasource methods of your table view to display the data.
That being said, it seems strange the the view controller is initiated with initWithCoder. That is usually the method invoked by storyboard for views.
I used two object when saving the post. It worked perfectly!
PFObject *quoteNew = [PFObject objectWithClassName:#"New"];
[quoteNew setObject:[[self attribution] text] forKey:#"by"];
[quoteNew setObject:[[self quoteText] text] forKey:#"quoteText"];
[quoteNew setObject:[[self attributionTitle] text] forKey:#"title"];
[quoteNew saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
[self done:self];
} else {
[[[UIAlertView alloc] initWithTitle:#"Uh oh. Somthing went wrong"
message:[[error userInfo] objectForKey:#"error"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] show];
}
}];
PFObject *quote = [PFObject objectWithClassName:#"Funny"];
[quote setObject:[[self attribution] text] forKey:#"by"];
[quote setObject:[[self quoteText] text] forKey:#"quoteText"];
[quote setObject:[[self attributionTitle] text] forKey:#"title"];
[quote saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
[self done:self];
} else {
[[[UIAlertView alloc] initWithTitle:#"Uh oh. Somthing went wrong"
message:[[error userInfo] objectForKey:#"error"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] show];
}
}];
}

Checking if word is valid in array

I am using code to check if a word is in my array, if it is I want it to submit it and I have the code for it. If it isn't I want it to pop up a screen. now this all works, the only thing is the screen pops up 2 times, because there are 2 words in my array. here is the code to explain it a little better.
NSArray *searchContacts = [NSArray arrayWithObjects:
#"CADEAU",
#"KADERZ",nil];
NSString *myContact = labelsText.text;
for (NSString *contact in searchContacts) {
if ([contact isEqualToString:myContact]) {
this is where I put in my words, CADEAU & KADERZ in this case. When I put one of these words into labelsText.text it does exactly what I want. but for the else statement if the labels text.text word is not CADEAU or KADERZ, it pop ups a screen:
else {
UIAlertView *alert = [[UIAlertView alloc]
This screen will pup up 2 times now, so i'll have to press dismiss 2 times, how would I fix this to just have to press dismiss one time no mather how many words are in the array?
It would be more efficient to use an NSSet, but even if you use an NSArray, you can simply call containsObject: instead of looping through the collection yourself.
if (![searchContacts containsObject:myContact]) {
//show alert...
}
Put a break; after the code showing your alert:
for (NSString *contact in searchContacts) {
if ([contact isEqualToString:myContact]) {
// do something
} else {
// show screen
break;
}
}
This will 'break' out of the loop.
I think you want something like this:
BOOL contactFound = NO;
for (NSString *contact in array)
{
if ([contact isEqualToString:myContact])
{
contactFound = YES;
break;
}
}
if (!contactFound)
UIAlertView *alert = [[UIAlertView alloc]...
Use a break after your UIAlertView.
For example:
for (NSString *contact in searchContacts) {
if ([contact isEqualToString:myContact]) {
//do what you want to do
}
else{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert show];
break; //leave for()
}
}
Or use that:
searchContacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([contact isEqualToString:myContact]) {
//do what you want to do
}
else{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert show];
*stop = YES; //stop enumeration
}
}

Making selectedSegmentIndex select nothing after selection

I have a UISegmentControl that select nothing through IB, after the user selects the segment it becomes selected. How do i do it so that it doesnot gets selected?
//Show question method
-(void)question:(NSInteger)i
{
// Path to the plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"Question" ofType:#"plist"];
// Set the plist to an array
NSArray *array = [NSArray arrayWithContentsOfFile:path];
//Check the number of entries in the array
NSInteger numCount = [array count];
if(i <numCount)
{ NSDictionary *dict = [array objectAtIndex:i];//load array index 0 dictionary data
self.title = [NSString stringWithFormat:#"Question %d", i+1];//set the nav bar title
quest.text = [dict valueForKey:#"Question"];//Set the Question to storage
ans.text = [dict valueForKey:#"Answer"];//Set the Answer to storage
NSInteger option = [[dict valueForKey:#"NumberOfOption"] integerValue ];//Check options to determine the question type
//check if the option is is a QRCode or Multiple Choices Question
if (option ==0)
{
QRbutton.alpha = 1; //show the QR Code Button If there is no options
OptionsAnswer.alpha = 0;//Hide Option if there is no options
}
else
{
QRbutton.alpha = 0.0;//Hide QR Code Button if there is options
OptionsAnswer.alpha = 1;//Show Option if there is options
[OptionsAnswer setTitle:[dict valueForKey:#"Option1"] forSegmentAtIndex:0];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option2"] forSegmentAtIndex:1];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option3"] forSegmentAtIndex:2];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option4"] forSegmentAtIndex:3];//Set Option Answer Value
[OptionsAnswer addTarget:self action:#selector(OptionAnswerCheck) forControlEvents:UIControlEventValueChanged];//Call action when options is being selected
}
}
else {
//if question is all answered, it will prompt an alert for end game video.
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Well Done"
message:#"You Have Answered All The Questions, Oh Wait A Minute I Heard A Cracking Sound...." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
}
//Check if the selected Option is correct
-(IBAction)OptionAnswerCheck
{
//define a persistant location to save which question has been answered
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];//question storages
//pass the value from the selected option to a string
//NSString * selectedTitle = ([OptionsAnswer selectedSegmentIndex] >= 0) ? [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]] :
NSString * selectedTitle = [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]];
NSLog(#"Selected Title = %#",selectedTitle);//test
//check if the selected value is equal to the answers
if ([selectedTitle compare:self.ans.text] ==NSOrderedSame)
{
//Popup to say answer Correct
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Correct!"
message:#"Nice Work, Lets Move On To The Next Question" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
//increase the question number
[self question:++currentQuestion];
//save increased question
[userDefaults setInteger:currentQuestion forKey:#"currentQuestion"];
}
else
{
//Popup to say answer Wrong
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Incorrect"
message:#"Close! But That's Not Right, Try Another Answer" delegate:nil
cancelButtonTitle:#"Try Again." otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
//OptionsAnswer.selectedSegmentIndex = UISegmentedControlNoSegment;
}
Just search for setMomentary: in your developer documentation inside Xcode.
I'm not entirely sure what you're asking here, but I think that you want to set the momentary property toYES.
The property is in the inspector of IB as well. (Can't post a screenshot, I'm on my iPhone).