Crash [NSCalendar calendarWithIdentifier:] on ios 7 - ios

I've crashed app when my app run on iOS 7
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSCalendar calendarWithIdentifier:]: unrecognized selector sent to class 0x3b67718c'
I'm using the code on my project
- (instancetype)initWithLocale:(NSLocale *)locale andFirstWeekday:(NSUInteger)firstWeekday{
if (self = [super init]){
_calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
_calendar.timeZone = [NSTimeZone localTimeZone];
_calendar.locale = locale;
_calendar.firstWeekday = firstWeekday;
}
return self;
}
Someone guy please help me to solve that problem that help me save a ton of time in my life. Thanks.

[NSCalendar calendarWithIdentifier] is available for iOS 8+.
You can use initializer method instead, this works fine in all iOS:
_calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];

Related

How to crash a cordova ios app

I am trying to write a small sample of cordova ios application. One of my requirements is to provide a button/link to allow user to crash the application.
I have tried to raise exception in CDVUIWebViewNavigationDelegate.m as follows,
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL* url = [request URL];
if([url.path containsString:#"CRASH"])
{
NSLog(#"User crash bookmart with NSException");
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
NSDate *current = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; // Set date and time styles
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter stringFromDate:current];
[userInfo setObject:#"Crash Time" forKey:currentTime];
NSException *ex = [[NSException alloc] initWithName:#"BookmartCrashException" reason:#"User crashed bookmart!" userInfo:userInfo];
[ex raise];
}
...
}
But when I tried, I saw following log,
2017-09-04 17:09:57.148 HRent[96124:12077045] User crash bookmart with NSException
2017-09-04 17:09:57.149 HRent[96124:12077045] *** WebKit discarded an uncaught exception in the >webView:decidePolicyForNavigationAction:request:frame:decisionListener: delegate: User crashed bookmart!
The exception has been discarded and app hasn't crash : (
Is there any other way to crash the app for sure? Or with some configuration can I disable WebKit to discard such exception?
Much appreciate for your answers!
Regards
Rachel
Thanks Everyone.
I have tried with all the suggestion except for plugin suggested by Will.
Overall, there are 2 ways to crash the app.
As Michale suggested, use abort() to terminate the app.
Here is the piece of code I used,
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:
(UIWebViewNavigationType)navigationType
{
NSURL* url = [request URL];
if([url.path containsString:#"CRASH"])
{
abort();
}
...
}
As shebuka's suggested, dispatch the exception on main thread. The trick here is that we can not use accessing nil array or dividing 0 to raise this exception but have to write I post in my question. Otherwise, the app won't crash and no log shown.
Here is the code piece I used,
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:
(UIWebViewNavigationType)navigationType
{
NSURL* url = [request URL];
if([url.path containsString:#"CRASH"])
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"User crash bookmart with NSException");
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
NSDate *current = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; // Set date and time styles
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter stringFromDate:current];
[userInfo setObject:#"Crash Time" forKey:currentTime];
NSException *ex = [[NSException alloc] initWithName:#"BookmartCrashException" reason:#"User crashed bookmart!" userInfo:userInfo];
[ex raise];
});
} ...}
I am going to choose solution 2 cause this crashes app with an exception which fits my requirement better.
Thanks everyone.
Try to launch your exception with dispatch on the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
NSInteger asd = 5 / 0; // Simple division by 0
});
If it works then try NSException approach to have all that extra info.
Have you tried abort() as in the default core data implementation example? It causes the application to generate a crash log and terminate.
The hockeyapp plugin provides functionality that allows you to crash an app. You can use this as a temporary solution until you figure out the problem.
hockeyapp.forceCrash():void
Check out the repository https://github.com/Microsoft/cordova-plugin-hockeyapp

GADInterstitial crash in init

I'm adding Google Admob Fullscreen ads
m_interstitial = [[GADInterstitial alloc] initWithAdUnitID:ADMOB_FS_ID]; // crash here!!!
m_interstitial.delegate = self;
GADRequest* request = [GADRequest request];
request.testDevices = #[ #"XXXXXXXXXXXXXXXXXXXXXXXxxx" ];
[m_interstitial loadRequest:request];
But the app is crash at the init line.
I'm using the Admob ios sdk 7.3.1.
The crash report is below
2015-06-03 00:22:17.077 XXX[17213:4624660] -[GADInterstitialViewController setSlot:]: unrecognized selector sent to instance 0x14e4b6f0
2015-06-03 00:22:17.079 XXX[17213:4624660] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GADInterstitialViewController setSlot:]: unrecognized selector sent to instance 0x14e4b6f0'
*** First throw call stack:
(0x29e9a5a7 0x37a80c77 0x29e9fa6d 0x29e9d949 0x29dceb68 0x1dc9f4 0x19b8b4 0xd3923 0xe488d 0x2d3b437b 0x2d418553 0x2d4184dd 0x2d3945e7 0x29e61275 0x29e5e959 0x29e5ed5b 0x29dabb51 0x29dab963 0x312ea1a9 0x2d3fdc91 0x102011 0x38029aaf)
libc++abi.dylib: terminating with uncaught exception of type NSException
Whats the matter?
EDIT: My whole code is below
in AppDelegate.m
- (void)showNag
{
// GAD full
// m_interstitial = [[GADInterstitial alloc] initWithAdUnitID:ADMOB_FS_ID];
m_interstitial = [[GADInterstitial alloc] init];
m_interstitial.adUnitID = ADMOB_FS_ID;
m_interstitial.delegate = self;
GADRequest* request = [GADRequest request];
request.testDevices = #[ #"251a8278d43c4c1468ce2d807a0ccc72" ];
[m_interstitial loadRequest:request];
}
viewcontroller.m
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
AppDelegate* delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[delegate showNag];
}
I got it. I had the named GADViewController.h/m files. They made conflict with the GAD framework. The framework also has the same named files. I renamed my files and it works now.

Comparing NSDate and UIDatePicker ERROR

Trying to form an if statement which compares the current date on the left to the date chosen in UIDatePicker on the right, I think this is the right code I was given by a fellow Stack Overflow user, they shouldn't be able to perform this action, and they can't but I need to create a pop-up telling them why not:
//Get the current date
NSDate *pickerDate = [self.datePicker date];
//Unable to set notification for same day
//[datePicker setMinimumDate:[NSDate date]];
self.datePicker.date = [NSDate date];
if ([pickerDate compare:datePicker] == NSOrderedAscending) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Something wasn't right." message:#"That did not work and your alarm was not set." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
I am receiving the following error from implementing this:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIDatePicker timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0x10b9373a0'
Double check your call to the compare: method. You are comparing against the date picker instead of the date picker's date.
You want:
if ([pickerDate compare:datePicker.date] == NSOrderedAscending) {

MultiPeer MCNearbyBrowserService Crashing

I have an application that is using the MultiPeer Connectivity framework. Every time the application becomes active in AppDelegate, I make a new MCSession a MCNearbyBrowserService, and a MCNearbyAdvertiserService and call start browsing and start advertising. Then every time the application becomes inactive in AppDelegate, I stop browsing and advertising and set everything to nil. I find that MCNearbyBrowserService causes a crash in its syncQueue:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** - [__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[2]'
*** First throw call stack:
(0x2de3ee8b 0x381396c7 0x2dd7caef 0x2dd7c8b3 0x2f648167 0x2f6493af 0x3861e103 0x38622e77 0x3861ff9b 0x38623751 0x386239d1 0x3874ddff 0x3874dcc4)
libc++abi.dylib: terminating with uncaught exception of type NSException
sometimes when the app reopens.
Here is my code for applicationDidBecomeActive:
self.myIdentifier = [[MCPeerID alloc] initWithDisplayName:[self.class createHash:20]];
self.mainSession = [[MCSession alloc] initWithPeer:self.myIdentifier];
self.mainSession.delegate = self;
peerAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:self.myIdentifier discoveryInfo:nil serviceType: service];
peerAdvertiser.delegate = self;
peerBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:self.myIdentifier serviceType: service];
peerBrowser.delegate = self;
acceptReset = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(reset) userInfo:nil repeats:YES];
acceptPosts = true;
[peerBrowser startBrowsingForPeers];
[peerAdvertiser startAdvertisingPeer];
self.isBrowsing = true;
and here is my code for applicationWillResignActive:
[acceptReset invalidate];
[peerAdvertiser stopAdvertisingPeer];
[peerBrowser stopBrowsingForPeers];
[self.mainSession disconnect];
self.mainSession = false;
self.isBrowsing = false;
The full code can be viewed here: http://pastebin.com/E3wY6U4N
I remember running into this issue, and the quick fix was to nil out the delegates and release the browser and advertiser. So assuming your App Delegate has a strong property for each the setup method would look like:
self.peerAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:self.myIdentifier discoveryInfo:nil serviceType: service];
self.peerAdvertiser.delegate = self;
self.peerBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:self.myIdentifier serviceType: service];
self.peerBrowser.delegate = self;
And then when the app enters the background (or otherwise wants to stop browsing/advertising):
self.peerAdvertiser.delegate = nil;
[self.peerAdvertiser stopAdvertisingPeer];
self.peerAdvertiser = nil;
self.peerBrowser.delegate = nil;
[self.peerBrowser stopBrowsingForPeers];
self.peerBrowser = nil;
[self.mainSession disconnect];
I'd also recommend against creating a new MCPeerID on each app launch, as Multipeer Connectivity has a habit of discovering old peers, and you'll end up discovering your 'former self' on each relaunch.

Why does NSNotificationCenter post cause a" unrecognized selector sent to instance?"

I have an iPad app (XCode 4.6, Storyboards, iOS 6.2) with several classes. In one class, when I finish posting, I post a notification which I expect another class to catch. Not happening!
Here is the code to register the notifications, which I have in AppDelegate.m:
// add observers for notificaations
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(calendarTapNotification:)
name:#"calendarDateSelected" object:nil ];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(notificationOfAppointmentMade:)
name:#"appointmentMade" object:nil ];
Here is the code where I post a notification for one of the observers:
if(aDate != nil) { // if user tapped outside of valid date range, aDate will be nil
[passedData setObject:aDate forKey:#"selectedDate"];
// post notification CFGregorianDate has been tapped and pass selected date
[[NSNotificationCenter defaultCenter] postNotificationName:#"calendarDateSelected" object:self userInfo:passedData];
}
And this is the code where I handle the "calendarTapNotification" notification which never gets called:
- (void) calendarTapNotification:(NSNotification *) notification {
// was the calendar tapped?
if ([[notification name] isEqualToString:#"calendarDateSelected"]) {
// get the data in the dictiionary
NSDictionary *dict = [notification userInfo];
// NSLog(#"\ndict contents: %#", [dict objectForKey:#"selectedDate"]); // this is NSDate class!
// gets the year, month, and day for selected date
NSDate *selectedDate = [dict objectForKey:#"selectedDate"];
// NSLog(#"\n\ndict-selectedDate: %#", [dict objectForKey:#"selectedDate"]);
NSCalendar *calendar = [NSCalendar currentCalendar]; // get default calendar
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate: selectedDate];
// NSLog(#"\n\ndateFromComponents: %#", components);
// create start and end of date
NSDate *startDate = [self beginningOfDay: [calendar dateFromComponents:components]];
NSDate *endDate = [self endOfDay: [calendar dateFromComponents:components]];
// NSLog(#"\nstartDate: %# endDate: %#", startDate, endDate);
// create the predicate
NSPredicate *predicate = ([NSPredicate predicateWithFormat:#"((aStartTime > %#) AND (aStartTime <= %#))", startDate, endDate]);
// find all appointments with that selected date (AppointmentInfo is NSManagedContext; appointmentInfo is NSArray)
appointmentInfo = [AppointmentInfo MR_findAllWithPredicate:predicate];
SingletonAppointments *sharedInstance = [SingletonAppointments sharedInstance]; // initialize
// if(sharedInstance.globalApptList.count > 0) // <-------------- TODO
// [sharedInstance.globalApptList removeAllObjects]; //removeAllObjects]; // clear out the old stuff
if(appointmentInfo.count > 0) {
for (AppointmentInfo *appt in appointmentInfo) {
sharedInstance.globalApptList = appointmentInfo; // move data to sharedInstance
}
}
else {
sharedInstance.globalApptList = nil;
}
// NSLog(#"\n\nsharedInstance.count: %d", sharedInstance.globalApptList.count);
// re-draw the schedule
[self.subViewData setNeedsDisplay];
}
}
This is the output from the "crash":
2013-04-17 12:58:47.942 saori[11294:c07] -[AppDelegate calendarTapNotification:]: unrecognized selector sent to instance 0x8a25c60
2013-04-17 12:58:47.943 saori[11294:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppDelegate calendarTapNotification:]: unrecognized selector sent to instance 0x8a25c60'
* First throw call stack:
(0x2701012 0x19efe7e 0x278c4bd 0x26f0bbc 0x26f094e 0x14b04f9 0x275b0c5 0x26b5efa 0x13e4bb2 0x7de8 0x80eb 0x966cef 0x966f02 0x944d4a 0x936698 0x2b7edf9 0x2b7ead0 0x2676bf5 0x2676962 0x26a7bb6 0x26a6f44 0x26a6e1b 0x2b7d7e3 0x2b7d668 0x933ffc 0x297d 0x28a5 0x1)
libc++abi.dylib: terminate called throwing an exception
I have tried everything I know of, read the two Apple docs on NSNotifications and looked at Google and SO and found nothing)
Why doesn't it handler for notification get called? (which I suppose will lead to what is causing the crash).
Make sure you've implemented
calendarTapNotification:
notificationOfAppointmentMade:
in your AppDelegate.
If you have not implemented the calendarTapNotification: method then implement it, secondly make sure you are using the parameter for your method as you are using :.
When you are adding an observer for a notification then you should be able to listen to it, for listening to the notification, it should be posted. Make sure you are posting the calendarDateSelected notification in your code. I don't see anywhere you have posted.

Resources