iOS generating random message [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello this is the iOS project I'm working on .
I'm just a beginner at programming iOS apps.
I just need help so that I can improve ><
Here's my app so far.
So my job is under the reminder that shows the box " Daily Vibes".
I need to include 100 messages randomly.
I've heard of arc random function. I just need some examples on how to do use it.
Here's my code :
AppDelegate.m
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Daily Vibes"
message:notification.alertBody
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
AddtoDoViewController.m
implementation AddToDoViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.itemText.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)save:(id)sender {
[self.itemText resignFirstResponder];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = self.itemText.text;
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
// Dismiss the view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self.itemText resignFirstResponder];
return NO;
}
#end
I would like some assistance please.
Thank you.
Expectation :
With the box
Daily Vibes
-Attached 100 random messages-
Example of the affirmation :
NSarray *100affirmations = #[#"Every day in every way I am getting happier and happier.",
#"I am thankful to everybody who has touched my life and made it worth living. ",
#"Happiness is contagious. My happiness makes all these people happy, thus making it one big happy world.",
#"My happy disposition attracts happiness into my life and I only interact with happy people and have only happy experiences.",
#"I spread happiness to others and absorb happiness from others. I enjoy every moment of the day.",
#"Be happy is my motto and happiness is not a destination. It’s my way of life.",
#"I am living my life, feeling motivated and excited about the greatness I am creating, on a daily basis.",
#"I am going to make the best out of my life. I will appreciate all opportunities which are given to me and follow my way.",

Put your messages in an NSMutableArray and the following method will be good enough for your purposes I think:
+ (void) randomOrderedMutableArray:(NSMutableArray *) array
{
int count = [array count];
for (int i = 0; i < count; ++i)
{
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[array exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}

Related

Geolocation asynchronous iOS [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I would like to geolocalize in the background with a thred! But I can not, I tried scheduler, thred, operation ect ect ... but all I block the progress of the progressBar.
I use a singleton object for the location like this...
#implementation LocationManager
#pragma mark - singleton method
+ (LocationManager*)sharedInstance
{
static dispatch_once_t predicate = 0;
__strong static id sharedObject = nil;
dispatch_once(&predicate, ^{
sharedObject = [[self alloc] init];
});
return sharedObject;
}
#pragma mark - instance methods
-(id) init {
if (self = [super init]) {
_currentLocation = [[CLLocation alloc] init];
_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
_locationManager.delegate = self;
}
return self;
}
- (void)start
{
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//if the time interval returned from core location is more than two minutes we ignore it because it might be from an old session
if ( abs((int) [newLocation.timestamp timeIntervalSinceDate: [NSDate date]]) < 120) {
self.currentLocation = newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
// [[[UIAlertView alloc] initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}
#end
Then I just need to call...
[[LocationManager sharedInstance] start];
and the singleton will start tracking location.
Than I call...
[[LocationManager sharedInstance] currentLocation];
for the current location.
You can then use this to pass into the already asynchronous methods of CLGeocoder.
You can't rely on starting the location tracking and then instantly having the location. You need to use a method like this.
CLGeocoder is running in background.

for loop with array ios [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have to find a way to check (at the touch of a button) if the text in a textfield is present in an xml file.
I thought that if I load the xml file as an array then I could use a for loop to see if it is the same result as in the array.
are not at all practical for loops, could you explain me how can I write the code for this kind of problem?
I want that if the object is not present in the whole array then show the alert
thanks
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
cose = [[NSArray alloc] initWithObjects:#"giovanni",#"giulio",#"ciccio",#"panzo", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)prova {
for (NSString *myElement in cose) {
if ([myElement isEqualToString:textfield1.text]) {
label1.text = textfield1.text;
}
else {
UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:#"Attenzione!" message:#"connessione assente" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alertCellulare show];
}
}
}
With fast-enumeration:
-(IBAction)prova
{
BOOL present = NO;
for (NSString *myElement in cose) {
if ([myElement isEqualToString:textfield1.text]) {
label1.text = textfield1.text;
present = YES;
break;
}
}
if (!present){
UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:#"Attenzione!" message:#"connessione assente" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alertCellulare show];
}
}
with block based enumeration
-(IBAction)prova
{
__block BOOL present = NO;
[cose enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL *stop){
if ([name isEqualToString:textfield1.text]) {
label1.text = textfield1.text;
present = YES;
*stop = YES;
}
}];
if (!present){
UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:#"Attenzione!" message:#"connessione assente" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alertCellulare show];
}
}
Why not use a For-In loop (fast enumeration)?
Something like this:
for (NSString *myElement in myArray) {
if ([myElement isEqualToString:myTextField.text]) {
// Do something
}
}

How to add a textfield to an NSMutableArray

I'm trying to present what was entered into a textfield into a nsmutable array that will later be displayed.
I think that the problem is in the -(void)viewDidLoad method but I included all of the code just in case. The catch is that I will be leaving this page and then returning to it after another piece of information is selected. As this happens, I need to keep track of EACH thing that was entered into the textfield. Thanks for any help!
#import "EnteringCoursesViewController.h"
#import "SelectRotationController.h"
#implementation EnteringCoursesViewController
#synthesize classField;
#synthesize indicatedClass;
#synthesize labelClassTitle;
#synthesize selectRotationController;
#synthesize classesEnteredTable;
- (IBAction)chooseType {
UIActionSheet *typeSheet = [[UIActionSheet alloc]
initWithTitle:#"Class types"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:#"Core Class", #"Elective", nil];
[typeSheet showInView:self.view];
[typeSheet release];
}
- (void)actionSheet:(UIActionSheet *)typeSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
self.indicatedClass = classField.text;
NSString *indicatedString = indicatedClass;
NSString *greeting = [[NSString alloc]
initWithFormat:#"%# meets 6 times per rotation", indicatedString];
labelClassTitle.text = greeting;
labelClassTitle.hidden = NO;
[greeting release];
[indicatedClass release];
}
else if (buttonIndex == 1) {
self.indicatedClass = classField.text;
NSString *indicatedString = indicatedClass;
NSString *greeting = [[NSString alloc]
initWithFormat:#"%# meets 3 times per rotation", indicatedString];
labelClassTitle.text = greeting;
labelClassTitle.hidden = NO;
[greeting release];
[indicatedClass release];
}
}
- (IBAction)chooseFirstMeeting:(id)sender {
SelectRotationController *selectView = [[SelectRotationController alloc]
initWithNibName:#"SelectRotationController"
bundle:[NSBundle mainBundle]];
[selectView.navigationItem setTitle:#"First Period Day Choose"];
[self.navigationController pushViewController:self.selectRotationController animated:YES];
self.selectRotationController = selectView;
[selectView release];
}
- (IBAction)enteredClassText:(id)sender {
NSMutableArray *classesEntered = [[NSMutableArray alloc] init];
[classesEntered addObject:indicatedClass];
[classesEntered release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad {
self.navigationItem.hidesBackButton = YES;
[super viewDidLoad];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[classField release];
[labelClassTitle release];
[indicatedClass release];
[selectRotationController release];
[classesEnteredTable release];
[super dealloc];
}
#end
If viewDidLoad is called "indicatedClass" is not yet initialised and therefore nil.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
Important Raises an NSInvalidArgumentException if anObject is nil.
If you want to save that by leaving the view, add the addObject-Call in the viewDidUnload-method. Definitely you should check if the value is nil ;)
I dont see any alloc for your variable indicatedClass but an release!? It might be that the variable doesnt exists if viewDidUnload is calling.
EDIT
You init an NSMutableArray, add the object to this array and after that you released that object. Therefore the Data is away. You must save your array therewith you can use the content later. Keyword: NSUserDefaults ;)
Check also of nil values:
- (IBAction)enteredClassText:(id)sender {
if (indicatedClass != nil) {
NSMutableArray *classesEntered = [[NSMutableArray alloc] init];
[classesEntered addObject:indicatedClass];
[classesEntered release];
}
}
If the sender is an UILabel you can also use this snippet:
- (IBAction)enteredClassText:(id)sender {
if (sender.text != nil) {
NSMutableArray *classesEntered = [NSMutableArray arrayWithObject:sender.text];
// TODO: Save your array to NSUserDefaults...
}
}

Local Notification repetation at different times

I have an app that generates prayer times (5 times a day) i want to create notfication for the 5 prayers but the issue is the times change everyday based on some calculations.
Edit:
The calculations are done based on GPS location so when the user changes to another city the times will be updated accordingly. I input the date,timezone, GPS coordinates into a method and I get prayer time values in (HH:mm) format for that given day/location. Now I need to setup the Notfications. I'm not sure where to set them up.
here is the code
#import "PrayerTimeViewController.h"
#import "PrayTime.h"
#implementation PrayerTimeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:NSLocalizedString(#"PrayerTimes", nil)];
UIImage *i = [UIImage imageNamed:#"11-clock"];
[tbi setImage:i];
[i release];
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"Madinah"]];
self.view.backgroundColor = background;
[background release];
locationManager = [[CLLocationManager alloc]init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager startUpdatingLocation];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow];
if (t < -180) {
return;
}
PrayTime *prayerTime = [[PrayTime alloc]init];
[prayerTime setCalcMethod:0];
[prayerTime setFajrAngle:16];
[prayerTime setIshaAngle:14];
[prayerTime setAsrMethod:0];
NSDate *curentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* compoNents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:curentDate];
CLLocationCoordinate2D currLoc = [newLocation coordinate];
NSMutableArray *prayerCal = [prayerTime getDatePrayerTimes:[compoNents year] andMonth:[compoNents month] andDay:[compoNents day] andLatitude:currLoc.latitude andLongitude:currLoc.longitude andtimeZone:[[NSTimeZone localTimeZone] secondsFromGMT]/3600];
[prayerTime release];
[fajer setText:[prayerCal objectAtIndex:0]];
// UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSString *time = [prayerCal objectAtIndex:0];
NSString *dates = [NSString stringWithFormat:#"%d-%d-%d %#",[compoNents year],[compoNents month],[compoNents day],time];
NSDateFormatter *dateText = [[NSDateFormatter alloc]init];
[dateText setDateFormat:#"yyyy-MM-dd HH:mm"];
[dateText setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:[[NSTimeZone localTimeZone] secondsFromGMT]]];
NSLog(#"%#",[dateText dateFromString:dates]);
[shrooq setText:[prayerCal objectAtIndex:1]];
[duhur setText:[prayerCal objectAtIndex:2]];
[aser setText:[prayerCal objectAtIndex:3]];
[maghreb setText:[prayerCal objectAtIndex:5]];
[isha setText:[prayerCal objectAtIndex:6]];
[prayerCal release];
}
#end
You can use the repeatInterval parameter to repeat your five notifications, making them appear at the same time every day. Unfortunately there's no way to adjust the time without running your app.
You can run a GPS app in the background, though that would be quite a drain on the battery just for setting some timers. (This background process is really designed for GPS tracker apps. I'm not sure what Apple would make of using it for a slightly different purpose.)
But the easiest way would be just to update when the app is launched. When it launches you would get the current notifications (using the scheduledLocalNotifications property of UIApplication), cancel them if they're incorrect or out of date and create new ones. Each notification has a dictionary payload that you can use to make it easier to identify your alarms.

Xcode: Invalid parameter not satisfying

I keep running into a pretty frustrating error in Xcode after implementing a date picker. The error in the debugger is: "Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: date"
I've been going through my code for hours now, and can't find the issue. It may be because I'm not checking for nil, there is no date the first time the app installs and launches, so that may be causing the crash. If it is, how do I check for nil in this code? I'm still very new at programming, any help would be much appreciated. Here is the code:
#import "DatePickerViewController.h"
#implementation DatePickerViewController
#synthesize datePicker;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Initialization code
}
return self;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm'/'dd'/'yyyy"];
NSDate *eventDate = [[NSUserDefaults standardUserDefaults] objectForKey:#"DatePickerViewController.selectedDate"];
localNotif.fireDate = [eventDate dateByAddingTimeInterval:-13*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = #"Tomorrow!";
localNotif.alertAction = nil;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication]presentLocalNotificationNow:localNotif];
return YES;
}
- (void)viewDidLoad {
NSDate *storedDate = [[NSUserDefaults standardUserDefaults]
objectForKey:#"DatePickerViewController.selectedDate"];
[self.datePicker setDate:storedDate animated:NO];
}
- (IBAction)dateChanged:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *selectedDate = [self.datePicker date];
[defaults setObject:selectedDate forKey:#"DatePickerViewController.selectedDate"];
}
You don't check if date is null, before using it, in ex.
(void)viewDidLoad {
NSDate *storedDate = [[NSUserDefaults standardUserDefaults]
objectForKey:#"DatePickerViewController.selectedDate"];
// add this check and set
if (storedDate == nil) {
storedDate = [NSDate date];
}
// ---
[self.datePicker setDate:storedDate animated:NO];
}
I've find a Debug way may help you debug where is the exception occurred and may help someone to debug with exception.
navigate to breakpoint
Click the add button, and choose exception Breakpoint
Add breakpoint and make exception type to Objective-C
Run the code
It will stop at the line which make crash happened!
Hope this help~

Resources