iOS 5.0 ignoring NSSetUncaughtExceptionHandler? - exception

I've noticed some strange behavior in iOS 5: NSSetUncaughtExceptionHandler() doesn't seem to do anything anymore.
I have the following code:
static NSString* documentsDirectory()
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
static void handleException(NSException *exception)
{
// Write something to the documents dir
NSString* path = [documentsDirectory() stringByAppendingPathComponent:#"crashlog.txt"];
NSString* str = #"Handled exception";
NSError* err;
if(![str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err])
{
NSLog(#"Failed to write to file");
}
NSLog(#"Handled exception");
}
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSSetUncaughtExceptionHandler(&handleException);
[NSException raise:#"Test" format:#"Testing"];
...
}
The above code works on any device or simulator running 4.x or earlier. However, when I run it on the 5.0 simulator, the exception handler doesn't get called (doesn't write the file to the documents dir, doesn't log, and doesn't trigger if I set a breakpoint inside the handler).
Unfortunately, I don't have a 5.0 device available for testing, so I'm hoping someone could confirm that it's broken on 5.0 so I can file a bug report (or correct me, if there's a problem with my code).

Use iOS 6.0 SDK, build and run it on simulator 5.0! It works!
//////Code:
static NSString* documentsDirectory()
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
static void handleException(NSException *exception)
{
// Write something to the documents dir
NSString* path = [documentsDirectory() stringByAppendingPathComponent:#"crashlog.txt"];
NSString* str = #"Handled exception";
NSError* err;
if(![str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err])
{
NSLog(#"Failed to write to file");
}
NSLog(#"Handled exception");
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSSetUncaughtExceptionHandler(&handleException);
[NSException raise:#"Test" format:#"Testing"];
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[NSSetUncaughtExceptionHandlerTestViewController alloc] initWithNibName:#"NSSetUncaughtExceptionHandlerTestViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
//////Terminal log:
2012-10-09 20:06:24.726 NSSetUncaughtExceptionHandlerTest[7815:c07] Handled exception
2012-10-09 20:06:24.727 NSSetUncaughtExceptionHandlerTest[7815:c07] *** Terminating app due to uncaught exception 'Test', reason: 'Testing'
*** First throw call stack:
(0x14a4052 0xea4d0a 0x144ca78 0x144c9e9 0x29d7 0x129d6 0x138a6 0x22743 0x231f8 0x16aa9 0x138efa9 0x14781c5 0x13dd022 0x13db90a 0x13dadb4 0x13daccb 0x132a7 0x14a9b 0x28b2 0x27e5)
terminate called throwing an exception(lldb)

I'm seeing the same thing. It works on my iPad, but not in the simulator. If someone confirms on the phone, please feel free to edit this answer to reflect that.

Related

iOS web view application accessing the camera objc

I've asked a similar question before with android and now struggling with the same method in iOS. I have build a iOS application using UIwebview. how do I allow the web view to access the camera here is my code below
#import "ViewController.h"
#define YourURL #"https://XXXXXXXXXXX"
#interface ViewController ()<UIWebViewDelegate>
#property (nonatomic,strong)UIWebView *webView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.webView.scrollView.frame =self.webView.frame;
_webView.backgroundColor = [UIColor grayColor];
_webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
_webView.delegate = self;
if ([[[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]allKeys]containsObject:#"cookie"]) {
NSArray *cookies =[[NSUserDefaults standardUserDefaults] objectForKey:#"cookie"];
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName];
[cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue];
[cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain];
[cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath];
NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
}
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",YourURL]]];
_webView.scalesPageToFit = YES;
[ self.webView loadRequest:req];
[self.view addSubview:self.webView];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSArray *nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSHTTPCookie *cookie;
for (id c in nCookies)
{
if ([c isKindOfClass:[NSHTTPCookie class]])
{
cookie=(NSHTTPCookie *)c;
if ([cookie.name isEqualToString:#"PHPSESSID"]) {
NSNumber *sessionOnly = [NSNumber numberWithBool:cookie.sessionOnly];
NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure];
NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil];
[[NSUserDefaults standardUserDefaults] setObject:cookies forKey:#"cookie"];
break;
}
}
}
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(#"--------------%#",error);
}
#end
I have tried this but did not succeed gave me an error access camera from uiwebview?
the html coding
<!DOCTYPE html>
<html>
<head>
<title>///////</title>
<script type="text/javascript" src="../includes/instascan.min.js"></script>
</head>
<body>
<video id="preview" <?php /* style="position:fixed;right:0;bottom:0;min-width:100%;min-height:100%;" */ ?>></video>
<script type="text/javascript">
let opts = {
// Whether to scan continuously for QR codes. If false, use scanner.scan() to manually scan.
// If true, the scanner emits the "scan" event when a QR code is scanned. Default true.
continuous: true,
// The HTML element to use for the camera's video preview. Must be a <video> element.
// When the camera is active, this element will have the "active" CSS class, otherwise,
// it will have the "inactive" class. By default, an invisible element will be created to
// host the video.
video: document.getElementById('preview'),
// Whether to horizontally mirror the video preview. This is helpful when trying to
// scan a QR code with a user-facing camera. Default true.
mirror: false,
// Whether to include the scanned image data as part of the scan result. See the "scan" event
// for image format details. Default false.
captureImage: false,
// Only applies to continuous mode. Whether to actively scan when the tab is not active.
// When false, this reduces CPU usage when the tab is not active. Default true.
backgroundScan: true,
// Only applies to continuous mode. The period, in milliseconds, before the same QR code
// will be recognized in succession. Default 5000 (5 seconds).
refractoryPeriod: 5000,
// Only applies to continuous mode. The period, in rendered frames, between scans. A lower scan period
// increases CPU usage but makes scan response faster. Default 1 (i.e. analyze every frame).
scanPeriod: 1
};
let scanner = new Instascan.Scanner(opts);
scanner.addListener('scan', function (content) {
window.location = "result.php?result="+content;
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
if(cameras.length > 1){
scanner.start(cameras[1]);
}
else{
scanner.start(cameras[0]);
}
} else {
console.error('No cameras found.');
}
}).catch(function (e) {
console.error(e);
});
</script>
</body>
</html>
thank you in advance

Google Maps iOS SDK mylocation button not showing

I enabled myLocation and myLocationButton,
but it not showing on my view.
And I try log _mapView.myLocation it's nil.
I need to showing myLocation dot and myLocationButton.
Have some one can help me, thanks!
//
// ViewController.m
//
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <GoogleMaps/GoogleMaps.h>
#import "Reachability.h"
#interface ViewController ()<GMSMapViewDelegate,CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
CLLocation *currentLocations;
Reachability * udnReach;
};
#property (strong,nonatomic) GMSMapView * mapView;
#property (strong,nonatomic) NSDictionary * dic;
#property (nonatomic,strong) NSTimer * updatetimer;
#end
#implementation ViewController {
}
- (void)viewDidLoad {
locationManager =[[CLLocationManager alloc]init];
locationManager.delegate =self;
if ([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
[locationManager requestAlwaysAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.activityType = CLActivityTypeAutomotiveNavigation;
[locationManager startUpdatingLocation];
_mapView.delegate = self;
_mapView.myLocationEnabled = YES;
_mapView.settings.myLocationButton = YES;
//Map
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:locationManager.location.coordinate.latitude
longitude:locationManager.location.coordinate.longitude
zoom:16];
_mapView= [GMSMapView mapWithFrame:CGRectZero camera:camera];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(networkStatusChanged:) name:kReachabilityChangedNotification object:nil];
udnReach=[Reachability reachabilityWithHostName:#"google.com"];
// udnReach = [Reachability reachabilityForInternetConnection];
[udnReach startNotifier];
[self updatebike];
self.view = self.mapView;
NSLog(#"User's location: %#", _mapView.myLocation);
// Do any additional setup after loading the view, typically from a nib.
[super viewDidLoad];
}
i find to show button and get userlocation
// Rather than setting -myLocationEnabled to YES directly,
// call this method:
- (void)enableMyLocation
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusNotDetermined)
[self requestLocationAuthorization];
else if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted)
return; // we weren't allowed to show the user's location so don't enable
else
[self.view setMyLocationEnabled:YES];
}
// Ask the CLLocationManager for location authorization,
// and be sure to retain the manager somewhere on the class
- (void)requestLocationAuthorization
{
_locationAuthorizationManager = [[CLLocationManager alloc] init];
_locationAuthorizationManager.delegate = self;
[_locationAuthorizationManager requestAlwaysAuthorization];
}
// Handle the authorization callback. This is usually
// called on a background thread so go back to main.
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (status != kCLAuthorizationStatusNotDetermined) {
[self performSelectorOnMainThread:#selector(enableMyLocation) withObject:nil waitUntilDone:[NSThread isMainThread]];
_locationAuthorizationManager.delegate = nil;
_locationAuthorizationManager = nil;
}
}

Xcode:Reachability on additional view controller using storyboard

My app has 3 view controllers. VC#3(*Sponsor) takes the user to my website & so I am trying to implement Reachability for this VC. I added System Configuration framework & Apples Reachability .H & .M files to the project. Disabled ARC for Reachability .M file & VC#3 .M file. The project B&R fine, but I still do not get the pop up alert when disconnected from internet. I imported Reachability.h to VC#3 also. What am I missing?
VC#3(*Sponsor).M
#import "Sponsor.h"
#import "ViewController.h"
#interface Sponsor ()
#end
#implementation Sponsor
-(void)viewDidLoad {
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL
URLWithString:#"http://opticertificationprep.webs.com/"]]];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(IBAction)home:(id)sender{
}
- (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.
}
- (BOOL) hasInternet {
Reachability *reach = [Reachability
reachabilityWithHostName:#"www.opticertificationprep.webs.com"];
NetworkStatus internetStats = [reach currentReachabilityStatus];
if (internetStats == NotReachable) {
UIAlertView *alertOne = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Check Your Internet Connection" delegate:self cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alertOne show];
[alertOne release];
}
return YES;
}
For anyone with same problem. I was missing this bit of code in the the .M file. Once I added it my pop up alert works great.
`
-(void)viewDidLoad {
{
[super viewDidLoad];
[self hasInternet];
}
`

Cannot load the Google Maps view in iOS

I'm trying to load google maps view in iOS following the guide here
I created a new viewController for the map view called iptechMapViewController.h , iptechMapViewController.m and iptechMapViewController.xib
Here is the code in iptechMapViewController.m :
#import "iptechMapViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#interface iptechMapViewController ()
{
GMSMapView *mapView_;
}
#end
#implementation iptechMapViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)loadView
{
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.8683
longitude:151.2086
zoom:6];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
self.view = mapView_;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(-33.8683, 151.2086);
marker.title = #"Sydney";
marker.snippet = #"Australia";
marker.map = mapView_;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Then in another view controller named iptechFlipsideViewController.m I'm trying to show the iptechMapViewController as follows:
- (IBAction)showMap:(id)sender
{
iptechMapViewController *controller = [[iptechMapViewController alloc] initWithNibName:#"iptechMapViewController" bundle:nil];
[self.view addSubview:controller.view];
}
But after clicking the showMap button which is connected to the IBAction showMap, and after iOS asks permission to access my location alert appears and I touch OK, after that nothing shows up and in the console I get the following error"
Failed to make complete framebuffer object 8cd6
Thanks
Passing CGRectZero to mapWithFrame only works if the map view is the root view controller's root view - in which case it is resized to fit the screen. In your case since the map is a subview, you will need to specify a size when creating the map view.

Getting user specified information from URL in Objective C iOS

Currently I am working with a UIWebview which shows web content provided from a user. In this content there will be links to other web content and I need to decide whether to open links in safari or in the UIWebview.
My current solution is to add a queryString to the URL in the html e.g. <a href=http://www.w3schools.com?StayInApp target=_blank>Visit W3Schools</a>
When the user presses the link the following method in the UIViewController decides how to open the link.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSLog(#"%#",url);
NSLog(#"%#",[url scheme]);
NSLog(#"%#",[url user]);
NSLog(#"%#",[url query]);
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([[url query]isEqualToString:#"OutOfAppApp"]) {
NSLog(#"go out");
[[UIApplication sharedApplication] openURL:url];
return NO;
}
else if([[url query]isEqualToString:#"StayInApp"])
{
return YES;
}
}
return YES;
}
I do not have very much experience within web development and can therefore not see the consequences of using this approach. Is this a valid approach or should I use another way?
Regards
EDIT:
I have now come up with another approach using custom URL schemes, but I would still like comments on whether this is a valid solution :)
I have added a prefix to the links such as <a href=InAPP:http://www.w3schools.com target=_blank>Visit W3Schools</a>
When a user presses a link the app examines the prefix and decides whether to launch the rest of the url in the app or in safari. This is done with the following methods:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([[url scheme]isEqualToString:#"InAPP"]) {
NSLog(#"go in");
NSURLRequest *req=[NSURLRequest requestWithURL:[self removeExtensionFromURL:url]];
[[self browserView] loadRequest:req];
return NO;
}
else if([[url scheme]isEqualToString:#"OutAPP"])
{
NSLog(#"go out");
[[UIApplication sharedApplication] openURL:[self removeExtensionFromURL:url]];
return NO;
}
}
return YES;
}
-(NSURL*)removeExtensionFromURL:(NSURL*)url
{
NSMutableString *urlString=[NSString stringWithFormat:#"%#",url];
NSString *newURLString;
if ([[url scheme]isEqualToString:#"InAPP"]) {
newURLString = [urlString stringByReplacingOccurrencesOfString:#"InAPP:" withString:#""];
}
else if([[url scheme]isEqualToString:#"OutAPP"])
{
newURLString = [urlString stringByReplacingOccurrencesOfString:#"OutAPP:" withString:#""];
}
return [NSURL URLWithString:newURLString];
}