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
Related
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;
}
}
On iOS 8 I have a strange behavior regarding the navigation bar and orientation changes.
I have a navigation controller which reports a supported interface orientation UIInterfaceOrientationMaskLandscapeRight. The navigation bar has the expected height for landscape orientation (sadly I am not entitled to post screenshots).
Then I initiate a modal presentation of a view controller that only supports UIInterfaceOrientationMaskPortrait. When the presentation animation starts, it seems that the metrics of the underlying navigation controller are changed to a portrait presentation, as the height of the navigation bar grows to its portrait size, as depicted above.
iOS 7 does not exhibit this behavior. What am I missing? I want to restore the old behavior.
Here is the full code of the simple example above:
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
DOGButtonViewController *root = [DOGButtonViewController new];
DOGOrientedNavigationController *navi = [[DOGOrientedNavigationController alloc] initWithRootViewController:root];
navi.allowedInterfaceOrientations = UIInterfaceOrientationMaskLandscapeRight;
self.window.rootViewController = navi;
[self.window makeKeyAndVisible];
return YES;
}
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
}
#end
#implementation DOGOrientedNavigationController
- (NSUInteger)supportedInterfaceOrientations
{
return self.allowedInterfaceOrientations;
}
#end
#implementation DOGButtonViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Button View Controller";
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (IBAction)buttonClicked:(id)sender
{
DOGPortraitViewController *vc = [DOGPortraitViewController new];
[self presentViewController:vc animated:YES completion:nil];
}
#end
#implementation DOGPortraitViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Portrait Title";
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (IBAction)buttonClicked:(id)sender
{
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
#end
In a more complex setup I also experience the text in a UIWebView contained in the navigation controller being scaled up when presenting the portrait modal. When dismissing the modal, the text is not resized to its original size.
For lack of a better option I've done a bit of a hack for this.
Basically before I show the modal view I take a screen shot and lay it on top of the presenting view controller.
Obviously I have to remove this screen shot when the view re-appears
func showScreenShot () {
let image = screenShot()
self.screenShotImageView = UIImageView(image: image)
self.view.addSubview(self.screenShotImageView!)
}
func screenShot () -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, true, UIScreen.mainScreen().scale)
self.view.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image
}
func removeScreenShot () {
if let screenImageView = self.screenShotImageView {
screenImageView.removeFromSuperview()
self.screenShotImageView = nil
}
}
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.
Anyone else experiencing this? I'm using the latest Google Maps SDK for iOS. This is what I have in the didTapInfoWindowOfMarker method :
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(id<GMSMarker>)marker {
NSLog(#"yes");
}
Not getting any response in my output.
Sounds like you didn't add delegate and protocol for your GMSMapView object, something like:
mapView_.delegate = self;
in loadView method.
So, the full - (void)loadViewand delegate method should be:
#interface ViewController () <GMSMapViewDelegate> // Add this if you haven't
{
id<GMSMarker> myMarker;
}
- (void)loadView {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.8683
longitude:151.2086
zoom:6];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
mapView_.delegate = self; // This sets the delegate for map view
self.view = mapView_;
}
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(id<GMSMarker>)marker {
NSLog(#"yes"); // And now this should work.
}
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];
}