Ejemplo n.º 1
0
        public void StartBeacon()
        {
            _locationMgr.RequestAlwaysAuthorization();

            // Authorization
            _locationMgr.AuthorizationChanged += DidAuthorizationChanged;

            // Monitoring
            _locationMgr.RegionEntered += DidRegionEntered;
            _locationMgr.RegionEntered += DidRegionLeft;

            // Ranging
            _locationMgr.DidRangeBeacons   += DidRangeBeacons;
            _locationMgr.DidDetermineState += DidDetermineState;
            _locationMgr.PausesLocationUpdatesAutomatically = false;

            _locationMgr.StartUpdatingLocation();
            _locationMgr.RequestAlwaysAuthorization();

            _fieldRegion = new CLBeaconRegion(new NSUuid(AppConstants.AppUUID), "Covid19Radar");
            _fieldRegion.NotifyOnEntry             = true;
            _fieldRegion.NotifyOnExit              = true;
            _fieldRegion.NotifyEntryStateOnDisplay = true;
            _locationMgr.StartMonitoring(_fieldRegion);

            System.Diagnostics.Debug.WriteLine("Start");
        }
        protected override void StartMonitoringInternal(IList <BeaconModel> beaconList)
        {
            _locationManager.RequestAlwaysAuthorization();

            _locationManager.DidRangeBeacons   += LocationManager_DidRangeBeacons;
            _locationManager.DidDetermineState += LocationManager_DidDetermineState;;

            _locationManager.PausesLocationUpdatesAutomatically = false;

            _locationManager.StartUpdatingLocation();

            _locationManager.RequestAlwaysAuthorization();

            foreach (var beacon in beaconList)
            {
                var clBeaconRegion = new CLBeaconRegion(new NSUuid(beacon.UUID), beacon.Major, beacon.Minor, "custom_region_id");

                clBeaconRegion.NotifyEntryStateOnDisplay = true;
                clBeaconRegion.NotifyOnEntry             = true;
                clBeaconRegion.NotifyOnExit = true;

                _beaconRegions.Add(clBeaconRegion);

                _locationManager.StartMonitoring(clBeaconRegion);
                _locationManager.StartRangingBeacons(clBeaconRegion);

                Debug.WriteLine($"StartMonitoring {beacon.UUID}");
            }
        }
Ejemplo n.º 3
0
        public void StartBeacon()
        {
            System.Diagnostics.Debug.WriteLine("StartBeacon");

            _locationMgr.RequestAlwaysAuthorization();
            _locationMgr.DidRangeBeacons   += HandleDidRangeBeacons;
            _locationMgr.DidDetermineState += HandleDidDetermineState;
            _locationMgr.PausesLocationUpdatesAutomatically = false;
            _locationMgr.StartUpdatingLocation();
            _locationMgr.RequestAlwaysAuthorization();

            _listOfCLBeaconRegion.Add(clBeaconRegion);
            _locationMgr.StartMonitoring(clBeaconRegion);
            _locationMgr.StartRangingBeacons(clBeaconRegion);

            //            #if DEBUG
            //            var beacon = _listOfCLBeaconRegion.First();
            //            string uuid = beacon.ProximityUuid.AsString ();
            //            var major = (ushort)beacon.Major;
            //            var minor = (ushort)beacon.Minor;
            //
            //            Mvx.Resolve<IMvxMessenger>().Publish<BeaconChangeProximityMessage> (
            //                new BeaconChangeProximityMessage (this, uuid, major, minor)
            //            );
            //            #endif
        }
Ejemplo n.º 4
0
        public static async Task <AccessState> RequestAccess(this CLLocationManager locationManager, bool background)
        {
            var status = locationManager.GetCurrentStatus(background);

            if (status != AccessState.Unknown)
            {
                return(status);
            }

            var task = locationManager
                       .WhenAccessStatusChanged(background)
                       .Take(1)
                       .ToTask();

#if __IOS__
            if (background)
            {
                locationManager.RequestAlwaysAuthorization();
            }
            else
            {
                locationManager.RequestWhenInUseAuthorization();
            }
#elif !__TVOS__
            locationManager.RequestAlwaysAuthorization();
#endif

            status = await task;
            return(status);
        }
Ejemplo n.º 5
0
        public void RequestAccess(AccessType accessType)
        {
            _AccessType = accessType;
            var s = (accessType == AccessType.Full) ? "requestAlwaysAuthorization" : "requestWhenInUseAuthorization";

            if (_Manager.RespondsToSelector(new Selector(s)))
            {
                _Manager.RequestAlwaysAuthorization();
            }
        }
Ejemplo n.º 6
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // create a new window instance based on the screen size
            Window = new UIWindow(UIScreen.MainScreen.Bounds);
            Window.RootViewController = new Table();

            // make the window visible
            Window.MakeKeyAndVisible();

            //GIMBAL - encapsulate gimbal service management and ios location into following class
            gimbalManager = new GimbalManager();
            //need an empty dictionary for the overload...just doesn't seem right, does it?
            var dict = NSDictionary.FromObjectAndKey((NSString)"nada", (NSString)"nidi");

            //sub out your api key here
            GimbalFramework.Gimbal.SetAPIKey("YOUR_API_KEY_HERE", dict);
            //if app was previously authorized, start up gimbal services
            if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways)
            {
                gimbalManager.Start();
            }

            //request always auth for location - need a listener since this happens async on start esp on first run
            CLLocationManager manager = new CLLocationManager();

            manager.Delegate = gimbalManager;
            manager.RequestAlwaysAuthorization();

            return(true);
        }
Ejemplo n.º 7
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            map = new MKMapView(View.Bounds)
            {
                AutoresizingMask = UIViewAutoresizing.FlexibleDimensions
            };


            //This LoadView function fix the resizing of the map problem, when zoomed in on user.
            LoadView();
            View.AddSubview(map);

            //Take a look at UIKit.UIView.SizeThatFits
            locationManager.RequestWhenInUseAuthorization();
            locationManager.RequestAlwaysAuthorization();
            map.ShowsUserLocation = true;

            UpdateMapFromUserLocation();
            SettingMaxSpeedForRun();
            SettingMinSpeedForRun();
            SettingTheDistanceOfRun();

            FlagForRun = true;
            StartFlag  = false;
            startButton.TouchUpInside += (object sender, System.EventArgs e) =>
            {
                StartFlag = !StartFlag;
            };
        }
Ejemplo n.º 8
0
        public static async Task <AccessState> RequestGpsAccess(this CLLocationManager locationManager, bool backgroundMode)
        {
            if (!CLLocationManager.LocationServicesEnabled)
            {
                return(AccessState.Disabled);
            }

            var gdelegate = (GpsManagerDelegate)locationManager.Delegate;
            var result    = CLLocationManager.Status;

            if (result == CLAuthorizationStatus.NotDetermined)
            {
                var tcs     = new TaskCompletionSource <CLAuthorizationStatus>();
                var handler = new EventHandler <CLAuthorizationStatus>((sender, status) => tcs.TrySetResult(status));
                gdelegate.AuthStatusChanged += handler;

                if (backgroundMode)
                {
                    locationManager.RequestAlwaysAuthorization();
                }
                else
                {
                    locationManager.RequestWhenInUseAuthorization();
                }

                result = await tcs.Task;
                gdelegate.AuthStatusChanged -= handler;
            }
            return(result.FromNative(backgroundMode));
        }
Ejemplo n.º 9
0
        public static async Task <AccessState> RequestGeofenceAccess(this CLLocationManager locationManager)
        {
            if (!CLLocationManager.LocationServicesEnabled)
            {
                return(AccessState.Disabled);
            }

            if (!CLLocationManager.IsMonitoringAvailable(typeof(CLCircularRegion)))
            {
                return(AccessState.NotSupported);
            }

            var gdelegate = (GeofenceManagerDelegate)locationManager.Delegate;
            var result    = CLLocationManager.Status;

            if (result == CLAuthorizationStatus.NotDetermined)
            {
                var tcs     = new TaskCompletionSource <CLAuthorizationStatus>();
                var handler = new EventHandler <CLAuthorizationStatus>((sender, status) => tcs.TrySetResult(status));
                gdelegate.AuthStatusChanged += handler;
                locationManager.RequestAlwaysAuthorization();

                result = await tcs.Task;
                gdelegate.AuthStatusChanged -= handler;
            }
            return(result.FromNative(true));
        }
Ejemplo n.º 10
0
        public void LocationManagerInit()
        {
            this.locMgr = new CLLocationManager();
            this.locMgr.PausesLocationUpdatesAutomatically = false;
            // iOS 8 has additional permissions requirements
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                locMgr.RequestAlwaysAuthorization(); // works in background
                                                     //locMgr.RequestWhenInUseAuthorization (); // only in foreground
            }
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                locMgr.AllowsBackgroundLocationUpdates = true;
            }
            if (CLLocationManager.LocationServicesEnabled)
            {
                //set the desired accuracy, in meters

                locMgr.DesiredAccuracy   = 1;
                locMgr.LocationsUpdated += async(object sender, CLLocationsUpdatedEventArgs e) =>
                {
                    // fire our custom Location Updated event
                    //LocationUpdated(this, new LocationUpdatedEventArgs(e.Locations[e.Locations.Length - 1]));
                    //await App.Locator.ClockIn.ClockInUpdateAsync();
                };

                locMgr.StartUpdatingLocation();
            }
        }
Ejemplo n.º 11
0
        public void SetUpLocationManger()
        {
            beaconUUID = new NSUuid(BeaconCreds.UUID);

            LocationManager = new CLLocationManager();
            LocationManager.RequestAlwaysAuthorization();
            LocationManager.StartUpdatingHeading();

            if (BeaconCreds.BeaconMonitoring == BeaconMonitoring.Proximity)
            {
                BeaconsRegion = new CLBeaconRegion(beaconUUID, BeaconCreds.BeaconsRegion);

                LocationManager.StartRangingBeacons(BeaconsRegion);
            }
            else
            {
                BeaconsRegionsList = new List <CLBeaconRegion>();

                foreach (Beacon beacon in Beacons.BeaconList)
                {
                    CLBeaconRegion tempRegion = new CLBeaconRegion(beaconUUID, (ushort)beacon.Major, (ushort)beacon.Minor, beacon.RegionId);
                    tempRegion.NotifyEntryStateOnDisplay = true;
                    tempRegion.NotifyOnEntry             = true;
                    tempRegion.NotifyOnExit = true;

                    BeaconsRegionsList.Add(tempRegion);

                    LocationManager.StartMonitoring(tempRegion);
                }
            }
        }
Ejemplo n.º 12
0
        private GeofenceMonitor()
        {
#if __UNIFIED__
            _locationManager = new CLLocationManager();
            _locationManager.DesiredAccuracy       = CLLocation.AccuracyBest;
            _locationManager.AuthorizationChanged += _locationManager_AuthorizationChanged;
            _locationManager.LocationsUpdated     += _locationManager_LocationsUpdated;
#if __IOS__
            _locationManager.AllowsBackgroundLocationUpdates = true;

            UIApplication.SharedApplication.BeginInvokeOnMainThread(() =>
            {
                _locationManager.RequestAlwaysAuthorization();
            });
            if (!CLLocationManager.IsMonitoringAvailable(typeof(CLCircularRegion)))
#else
            if (!CLLocationManager.IsMonitoringAvailable(new ObjCRuntime.Class("CLCircularRegion")))
#endif
            {
                Status = GeofenceMonitorStatus.NotAvailable;
            }
            else
            {
                maxRegion = _locationManager.MaximumRegionMonitoringDistance;
                _locationManager.RegionEntered += _locationManager_RegionEntered;
                _locationManager.RegionLeft    += _locationManager_RegionLeft;
            }
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE
            _monitor = Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.Current;
#elif TIZEN
            _locator                      = new Tizen.Location.Locator(Tizen.Location.LocationType.Hybrid);
            _locator.ZoneChanged         += _locator_ZoneChanged;
            _locator.ServiceStateChanged += _locator_ServiceStateChanged;
#endif
        }
Ejemplo n.º 13
0
        public Location(LisingType lisingType = LisingType.Foreground)
        {
            _locMgr = new CLLocationManager {
                PausesLocationUpdatesAutomatically = false
            };


            if (!UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                return;
            }
            switch (lisingType)
            {
            case LisingType.Foreground:
                _locMgr.RequestWhenInUseAuthorization();     // only in foreground
                break;

            case LisingType.Background:
                _locMgr.RequestAlwaysAuthorization();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(lisingType), lisingType, null);
            }
        }
Ejemplo n.º 14
0
        public LocationManager()
        {
            this.locMgr = new CLLocationManager();
            this.locMgr.PausesLocationUpdatesAutomatically = false;

            // iOS 8 has additional permissions requirements
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                locMgr.RequestAlwaysAuthorization();                 // works in background
                //locMgr.RequestWhenInUseAuthorization (); // only in foreground
            }

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                locMgr.AllowsBackgroundLocationUpdates = true;
            }

            _lastLocation       = new LocationTracker();
            _watchTowerSettings = SingletonManager.WatchTowerSettings;

            _bgWorkerWrapper = new BackgroundWorkerWrapper(new DelegateDefinitions.DoWorkOrWorkCompletedDelegate(PostLocation),
                                                           new DelegateDefinitions.DoWorkOrWorkCompletedDelegate(PostLocationCompleted),
                                                           _watchTowerSettings.UpdateInterval);

            StartLocationUpdates();
        }
Ejemplo n.º 15
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            locMan = new CLLocationManager();
            locMan.RequestWhenInUseAuthorization();
            locMan.RequestAlwaysAuthorization();
            // Geocode a city to get a CLCircularRegion,
            // and then use our location manager to set up a geofence
            button.TouchUpInside += (o, e) => {
                // clean up monitoring of old region so they don't pile up
                if (region != null)
                {
                    locMan.StopMonitoring(region);
                }

                // Geocode city location to create a CLCircularRegion - what we need for geofencing!
                var taskCoding = geocoder.GeocodeAddressAsync("Cupertino");
                taskCoding.ContinueWith((addresses) => {
                    CLPlacemark placemark = addresses.Result [0];
                    region = (CLCircularRegion)placemark.Region;
                    locMan.StartMonitoring(region);
                });
            };


            // This gets called even when the app is in the background - try it!
            locMan.RegionEntered += (sender, e) => {
                Console.WriteLine("You've entered the region");
            };

            locMan.RegionLeft += (sender, e) => {
                Console.WriteLine("You've left the region");
            };
        }
Ejemplo n.º 16
0
        public BeaconService(ISQLiteConnectionProvider sqliteConnectionProvider)
        {
            _connection = sqliteConnectionProvider.GetConnection();
            _connection.CreateTable <BeaconDataModel>();

            _beaconTransmitter = new CBPeripheralManager();
            _beaconTransmitter.StateUpdated += DidStateUpdated;

            _listOfCLBeaconRegion = new List <CLBeaconRegion>();
            _fieldRegion          = new CLBeaconRegion(new NSUuid(AppConstants.iBeaconAppUuid), "");
            _fieldRegion.NotifyEntryStateOnDisplay = true;
            _fieldRegion.NotifyOnEntry             = true;
            _fieldRegion.NotifyOnExit = true;

            // Monitoring
            _locationManager = new CLLocationManager();
            if (CLLocationManager.LocationServicesEnabled)
            {
                _locationManager.Delegate = this;
                _locationManager.PausesLocationUpdatesAutomatically = false;
                _locationManager.ShowsBackgroundLocationIndicator   = true;
                _locationManager.DistanceFilter = 1.0;
                _locationManager.AllowsBackgroundLocationUpdates = true;
                _locationManager.DidRangeBeacons      += DidRangeBeconsInRegionComplete;
                _locationManager.AuthorizationChanged += HandleAuthorizationChanged;
                _locationManager.RequestAlwaysAuthorization();
            }
        }
Ejemplo n.º 17
0
        public override bool FinishedLaunching(UIApplication application,
                                               NSDictionary launchOptions)
        {
            RegisterNotifications();

            LocationManager = new CLLocationManager();

            LocationManager.AuthorizationChanged += (s, e) =>
            {
                if (e.Status != CLAuthorizationStatus.AuthorizedAlways)
                {
                    return;
                }

                var region = new CLBeaconRegion(_regionUuid, "Evolve Region");

                LocationManager.RegionEntered += (s1, e1) => SendEnterNotification();
                LocationManager.RegionLeft    += (s1, e1) => SendExitNotification();

                LocationManager.StartMonitoring(region);
            };

            LocationManager.RequestAlwaysAuthorization();

            return(true);
        }
Ejemplo n.º 18
0
 public void MonitorBackgroundLocation()
 {
     locManager = new CLLocationManager();
     locManager.RequestAlwaysAuthorization();
     locManager.StartMonitoringSignificantLocationChanges();
     locManager.LocationsUpdated += LocationsUpdated;
 }
Ejemplo n.º 19
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

            RegisterNotifications();

            LocationManager = new CLLocationManager();
            BeaconRegion    = new CLBeaconRegion(RegionUuid, "ITCamp 2016");
            BeaconRegion.NotifyEntryStateOnDisplay = true;
            BeaconRegion.NotifyOnEntry             = true;
            BeaconRegion.NotifyOnExit = true;

            LocationManager.AuthorizationChanged += (s, e) =>
            {
                if (e.Status != CLAuthorizationStatus.AuthorizedAlways)
                {
                    return;
                }

                LocationManager.RegionEntered += (s1, e1) => SendNotification("Welcome to the Beacon Session");
                LocationManager.RegionLeft    += (s1, e1) => SendNotification("Goodbye remember to compile the evaluation form");

                LocationManager.StartMonitoring(BeaconRegion);
            };

            LocationManager.RequestAlwaysAuthorization();
            return(true);
        }
Ejemplo n.º 20
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Enable logs
            Accengage.SetLoggingEnabled(true);

            Accengage.Start();

            // Register for notification
            AccengageIOS.ACCNotificationOptions options = (AccengageIOS.ACCNotificationOptions.Alert | AccengageIOS.ACCNotificationOptions.Badge | AccengageIOS.ACCNotificationOptions.Sound);
            AccengageIOS.Accengage.Push.RegisterForUserNotificationsWithOptions(options);

            // Enable Geofence service if needed
            AccengageIOS.BMA4SLocationServices.SetGeofenceServiceEnabled(SampleHelpers.isGeofenceServiceEnabled());

            // Enable Beacon service if needed
            AccengageIOS.BMA4SLocationServices.SetBeaconServiceEnabled(SampleHelpers.isBeaconServiceEnabled());

            //init géoloc
            locationManager                 = new CLLocationManager();
            locationManager.Delegate        = new LocationManagerDelegate();
            locationManager.DistanceFilter  = CLLocationDistance.FilterNone;
            locationManager.DesiredAccuracy = CLLocation.AccuracyBest;
            locationManager.RequestAlwaysAuthorization();
            locationManager.StartUpdatingLocation();

            AccPushSource = new AccPushDelegate(this);
            AccengageIOS.Accengage.Push.Delegate = AccPushSource;

            return(true);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 位置情報利用の認証状態が変わった際に、位置情報のモニタリングを開始します。
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="status"></param>
        public override void AuthorizationChanged(CLLocationManager manager, CLAuthorizationStatus status)
        {
            var adapter = new DbAdapter_iOS();

            adapter.AddDeviceLog($"位置情報の認証状態が更新", status.ToString()); // TODO ステータス名表示に

            if (status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.AuthorizedWhenInUse)
            {
                //iBeacon領域判定の有効化
                if (CLLocationManager.IsMonitoringAvailable(typeof(CLBeaconRegion)))
                {
                    研究室領域.NotifyEntryStateOnDisplay = false;
                    研究室領域.NotifyOnEntry             = true;
                    研究室領域.NotifyOnExit = true;

                    manager.StartMonitoring(研究室領域);
                }

                //ジオフェンス領域の有効化
                if (CLLocationManager.IsMonitoringAvailable(typeof(CLCircularRegion)))
                {
                    foreach (var gr in 学内領域)
                    {
                        gr.NotifyOnEntry = true;
                        gr.NotifyOnExit  = true;
                        manager.StartMonitoring(gr);
                    }
                }
            }
            else
            {
                //位置情報利用の許可を貰う
                manager.RequestAlwaysAuthorization();
            }
        }
Ejemplo n.º 22
0
        public void StartTracking()
        {
            locationManager = new CLLocationManager
            {
                PausesLocationUpdatesAutomatically = false,
                AllowsBackgroundLocationUpdates    = true
            };

            locationManager.AuthorizationChanged += (s, args) =>
            {
                if (args.Status == CLAuthorizationStatus.Authorized)
                {
                    locationManager.DesiredAccuracy   = CLLocation.AccurracyBestForNavigation;
                    locationManager.LocationsUpdated += async(object sender, CLLocationsUpdatedEventArgs e) =>
                    {
                        var lastLocation = e.Locations.Last();
                        var newLocation  = new Models.Location(lastLocation.Coordinate.Latitude, lastLocation.Coordinate.Longitude);

                        await locationRepository.Save(newLocation);
                    };

                    locationManager.StartUpdatingLocation();
                }
            };

            locationManager.RequestAlwaysAuthorization();
        }
        void RequestAlwaysAuthorization()
        {
            CLAuthorizationStatus status = CLLocationManager.Status;

            if (status == CLAuthorizationStatus.AuthorizedWhenInUse || status == CLAuthorizationStatus.Denied)
            {
                string title   = (status == CLAuthorizationStatus.Denied) ? "Location services are off" : "Background location is not enabled";
                string message = "To use background location you must turn on 'Always' in the Location Services Settings";

                UIAlertView alertView = new UIAlertView(title, message, null, "Cancel", "Settings");


                alertView.Clicked += (sender, buttonArgs) =>
                {
                    if (buttonArgs.ButtonIndex == 1)
                    {
                        // Send the user to the Settings for this app
                        NSUrl settingsUrl = new NSUrl(UIApplication.OpenSettingsUrlString);
                        UIApplication.SharedApplication.OpenUrl(settingsUrl);
                    }
                };

                alertView.Show();
            }
            else if (status == CLAuthorizationStatus.NotDetermined)
            {
                locationManager.RequestAlwaysAuthorization();
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            ApplyStylesToViews();

            locationManager.RequestAlwaysAuthorization();
            locationManager.RequestWhenInUseAuthorization();
            locationManager.DesiredAccuracy   = CLLocation.AccuracyBest;
            locationManager.LocationsUpdated += LocationManager_LocationsUpdated;
            locationManager.StartUpdatingLocation();

            mapHelper = new MapHelperFunctions("AIzaSyAZQBaY-ugQuwCWr4NkD-bybK7urElvNyY", googleMap);

            pickupButtonBar.TouchUpInside      += PickupButtonBar_TouchUpInside;
            destinationButtonBar.TouchUpInside += DestinationButtonBar_TouchUpInside;
            doneButton.TouchUpInside           += DoneButton_TouchUpInside;
            requestCabButton.TouchUpInside     += RequestCabButton_TouchUpInside;
            cancelRequestButton.TouchUpInside  += CancelRequestButton_TouchUpInside;

            menuButton.UserInteractionEnabled = true;
            menuButton.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                if (tripStage == 0)
                {
                    // display our side menu
                }
                else if (tripStage == 1)
                {
                    UIView.Animate(0.2, HideTripDetailsView);
                    ClearTripOnMap();
                }
            }));
        }
Ejemplo n.º 25
0
        public LocationManager()
        {
            _manager = new CLLocationManager();
            _locationChangeRegistry = LocationChangeRegistry.Instance;
            _manager.PausesLocationUpdatesAutomatically = false;

            // iOS 8 has additional permissions requirements
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                Console.WriteLine("GeoClient is running in iOS 8 or higher. 'RequestAlwaysAuthorization' is requested async.");
                _manager.RequestAlwaysAuthorization(); // works in background
            }

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                Console.WriteLine("GeoClient is running in iOS 9 or higher. 'AllowsBackgroundLocationUpdates' is set to true.");
                _manager.AllowsBackgroundLocationUpdates = true;
            }

            _manager.LocationsUpdated += (sender, e) =>
            {
                Console.WriteLine("Got a location update from location manager.");
                if (e.Locations.Length > 0)
                {
                    var lastLocation = e.Locations[e.Locations.Length - 1];
                    InformRegistryAboutLocationUpdate(lastLocation);
                }
                else
                {
                    Console.WriteLine("Got a location update without locations!");
                }
            };
        }
Ejemplo n.º 26
0
        public void didAuthorizationChange(CLAuthorizationChangedEventArgs authStatus)
        {
            switch (authStatus.Status)
            {
            case CLAuthorizationStatus.AuthorizedAlways:
                locationManager.RequestAlwaysAuthorization();
                break;

            case CLAuthorizationStatus.AuthorizedWhenInUse:
                locationManager.StartUpdatingLocation();
                break;

            case CLAuthorizationStatus.Denied:
                UIAlertView alert = new UIAlertView();

                alert.Title = "Location Services Disabled";
                alert.AddButton("OK");
                alert.AddButton("Cancel");
                alert.Message        = "Enable locations for this app via\nthe Settings app on your iPhone";
                alert.AlertViewStyle = UIAlertViewStyle.Default;

                alert.Show();

                alert.Clicked += (object s, UIButtonEventArgs ev) =>
                {
                    var Button = ev.ButtonIndex;
                };
                break;

            default:
                break;
            }
        }
Ejemplo n.º 27
0
        private static void RequestLocationAlways()
        {
            var status = CLLocationManager.Status;

            if (status != CLAuthorizationStatus.NotDetermined &&
                status != CLAuthorizationStatus.AuthorizedWhenInUse)
            {
                RaiseAuthorizationRequested(AuthorizationType.LocationAlways, status.ToShared(true));
                return;
            }

            if (_requests.TryGetValue(AuthorizationType.LocationAlways, out var value1))
            {
                var result = _requests.TryUpdate(AuthorizationType.LocationAlways, value1 + 1, value1);
            }
            else if (_requests.ContainsKey(AuthorizationType.LocationWhenUse))
            {
                var result = _requests.TryAdd(AuthorizationType.LocationAlways, 1);
            }
            else
            {
                _requests.TryAdd(AuthorizationType.LocationAlways, 1);
                _locationManager = new CLLocationManager();
                _locationManager.AuthorizationChanged += OnLocationRequested;
                _locationManager.RequestAlwaysAuthorization();
            }
        }
Ejemplo n.º 28
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            locMan = new CLLocationManager();
            locMan.RequestWhenInUseAuthorization();
            locMan.RequestAlwaysAuthorization();
            // Geocode a city to get a CLCircularRegion,
            // and then use our location manager to set up a geofence
            button.TouchUpInside += (o, e) => {

                // clean up monitoring of old region so they don't pile up
                if(region != null)
                {
                    locMan.StopMonitoring(region);
                }

                // Geocode city location to create a CLCircularRegion - what we need for geofencing!
                var taskCoding = geocoder.GeocodeAddressAsync ("Cupertino");
                taskCoding.ContinueWith ((addresses) => {
                    CLPlacemark placemark = addresses.Result [0];
                    region = (CLCircularRegion)placemark.Region;
                    locMan.StartMonitoring(region);

                });
            };

            // This gets called even when the app is in the background - try it!
            locMan.RegionEntered += (sender, e) => {
                Console.WriteLine("You've entered the region");
            };

            locMan.RegionLeft += (sender, e) => {
                Console.WriteLine("You've left the region");
            };
        }
Ejemplo n.º 29
0
        public void Initial()
        {
            manager = new CLLocationManager();
            //manager.Delegate = new MyLocationDelegate();

            manager.AllowsBackgroundLocationUpdates = true;

            manager.RequestWhenInUseAuthorization();

            manager.RequestAlwaysAuthorization();


            this.beaconregin = new CLBeaconRegion(new NSUuid("FDA50693-A4E2-4FB1-AFCF-C6EB07647826"), "myregion");

            this.beaconregin.NotifyEntryStateOnDisplay = true;
            this.manager.DesiredAccuracy = 100;
            this.manager.DistanceFilter  = 100;
            this.manager.AllowsBackgroundLocationUpdates = true;


            //this.manager.LocationsUpdated += Manager_LocationsUpdated;

            //this.manager.StartRangingBeacons(this.beaconregin);

            //this.manager.RegionEntered += Manager_RegionEntered;

            this.manager.DidRangeBeacons += Manager_DidRangeBeacons;
            //throw new NotImplementedException();
        }
Ejemplo n.º 30
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            NearBridgeiOS.Init("YOUR_API_KEY");

            UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(7200);

            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) => {
            });
            // set a notification delegate
            UNUserNotificationCenter.Current.Delegate = new UserNotificationDelegate();

            CLLocationManager LocationManager = new CLLocationManager();

            LocationManager.AuthorizationChanged += (s, e) =>
            {
                if (e.Status == CLAuthorizationStatus.AuthorizedAlways)
                {
                    NearBridgeiOS.Start();
                }
            };

            LocationManager.RequestAlwaysAuthorization();

            LoadApplication(new App());

            return(base.FinishedLaunching(app, options));
        }
Ejemplo n.º 31
0
 public void activarGPS()
 {
     try
     {
         this.locMgr = new CLLocationManager();
         this.locMgr.PausesLocationUpdatesAutomatically = false;
         if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
         {
             locMgr.RequestAlwaysAuthorization();
         }
         if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
         {
             locMgr.AllowsBackgroundLocationUpdates = true;
         }
         if (CLLocationManager.LocationServicesEnabled)
         {
             locMgr.DesiredAccuracy   = 1;
             locMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
             {
                 loc = new Dictionary <string, string>();
                 loc.Add("Lat", e.Locations[e.Locations.Length - 1].Coordinate.Latitude.ToString());
                 loc.Add("Lon", e.Locations[e.Locations.Length - 1].Coordinate.Longitude.ToString());
                 System.Diagnostics.Debug.WriteLine("Detectando(Lat : " + loc["Lat"] + ", Lon : " + loc["Lon"] + ")");
             };
             locMgr.StartUpdatingLocation();
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
 }
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

            _locationManager = new CLLocationManager();
            _locationManager.AuthorizationChanged += LocationManagerAuthorizationChanged;

            _locationManager.RequestAlwaysAuthorization();

            return true;
        }
Ejemplo n.º 33
0
		public LocationManager ()
		{
			this.locMgr = new CLLocationManager();
			// iOS 8 has additional permissions requirements
			//
			if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
				locMgr.RequestAlwaysAuthorization (); // works in background
				//locMgr.RequestWhenInUseAuthorization (); // only in foreground
			}

			LocationUpdated += PrintLocation;

		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            _locationManager = new CLLocationManager();
            _locationManager.AuthorizationChanged += LocationManagerAuthorizationChanged;
            _locationManager.DidRangeBeacons += LocationManagerDidRangeBeacons;

            _locationManager.RequestAlwaysAuthorization();

            _region = new CLBeaconRegion(new NSUuid("18E1FDEA-15E6-425E-B88C-2642B8F3C378"), "MyRegion");
        }
        protected override void PlatformSpecificStart(MvxLocationOptions options)
        {
            lock (this)
            {
                if (_locationManager != null)
                    throw new MvxException("You cannot start the MvxLocation service more than once");

                _locationManager = new CLLocationManager();
                _locationManager.Delegate = new LocationDelegate(this);

                if (options.MovementThresholdInM > 0)
                {
                    _locationManager.DistanceFilter = options.MovementThresholdInM;
                }
                else
                {
                    _locationManager.DistanceFilter = CLLocationDistance.FilterNone;
                }
                _locationManager.DesiredAccuracy = options.Accuracy == MvxLocationAccuracy.Fine ? CLLocation.AccuracyBest : CLLocation.AccuracyKilometer;
                if (options.TimeBetweenUpdates > TimeSpan.Zero)
                {
                    Mvx.Warning("TimeBetweenUpdates specified for MvxLocationOptions - but this is not supported in iOS");
                }


				if (options.TrackingMode == MvxLocationTrackingMode.Background)
				{
					if (IsIOS8orHigher)
					{
						_locationManager.RequestAlwaysAuthorization ();
					}
					else
					{
						Mvx.Warning ("MvxLocationTrackingMode.Background is not supported for iOS before 8");
					}
				}
				else
				{
					if (IsIOS8orHigher)
					{
						_locationManager.RequestWhenInUseAuthorization ();
					}
				}

                if (CLLocationManager.HeadingAvailable)
                    _locationManager.StartUpdatingHeading();

                _locationManager.StartUpdatingLocation();
            }
        }
Ejemplo n.º 36
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            _locationManager = new CLLocationManager();
            _locationManager.Delegate = new MyLocationDelegate();

            // Enable location mode, request if not authorized
            if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) {
                _locationManager.StartMonitoringSignificantLocationChanges ();
            } else {
                _locationManager.RequestAlwaysAuthorization ();
            }
        }
Ejemplo n.º 37
0
		public LocationManager ()
		{
			this.locMgr = new CLLocationManager ();

			this.locMgr.PausesLocationUpdatesAutomatically = false; 

			// iOS 8 has additional permissions requirements
			if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
				locMgr.RequestAlwaysAuthorization (); // works in background
				//locMgr.RequestWhenInUseAuthorization (); // only in foreground
			}

			if (UIDevice.CurrentDevice.CheckSystemVersion (9, 0)) {
				locMgr.AllowsBackgroundLocationUpdates = true;
			}
			LocationUpdated += PrintLocation;
		}
Ejemplo n.º 38
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            AppDelegate.Self = this;
            global::Xamarin.Forms.Forms.Init();
            App.ScreenSize = new Size(UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height);
            LoadApplication(new App());

            LocationManager = new CLLocationManager();
            var iOSVersion = UIDevice.CurrentDevice.SystemVersion.Split('.');
            if (Convert.ToInt32(iOSVersion[0]) >= 8)
            {
                LocationManager.RequestAlwaysAuthorization();
                LocationManager.RequestWhenInUseAuthorization();
            }

            return base.FinishedLaunching(app, options);
        }
Ejemplo n.º 39
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			// Perform any additional setup after loading the view, typically from a nib.

			var LocationManager = new CLLocationManager();
			LocationManager.RequestWhenInUseAuthorization ();
			LocationManager.RequestAlwaysAuthorization ();

			CLCircularRegion region = new CLCircularRegion (new CLLocationCoordinate2D (+46.833120, +15.34901), 1000.0, "FF Gussendorf");

			if (CLLocationManager.LocationServicesEnabled) {

				LocationManager.DidStartMonitoringForRegion += (o, e) => {
					Console.WriteLine ("Now monitoring region {0}", e.Region.ToString ());
				};

				LocationManager.RegionEntered += (o, e) => {
					Console.WriteLine ("Just entered " + e.Region.ToString ());
				};

				LocationManager.RegionLeft += (o, e) => {
					Console.WriteLine ("Just left " + e.Region.ToString ());
				};

				LocationManager.Failed += (o, e) => {
					Console.WriteLine (e.Error);
				};

				LocationManager.UpdatedLocation += (o, e) => {
					Console.WriteLine ("Lat " + e.NewLocation.Coordinate.Latitude + ", Long " + e.NewLocation.Coordinate.Longitude);
				};

				LocationManager.LocationsUpdated += (o, e) => Console.WriteLine ("Location change received");

				LocationManager.StartMonitoring (region);
				LocationManager.StartMonitoringSignificantLocationChanges ();

				//LocationManager.StopMonitoringSignificantLocationChanges ();



			} else {
				Console.WriteLine ("This app requires region monitoring, which is unavailable on this device");
			}
		}
Ejemplo n.º 40
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            var userNotificationSettings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert, new NSSet());
            UIApplication.SharedApplication.RegisterUserNotificationSettings(userNotificationSettings);

            _beaconRegion = new CLBeaconRegion(new NSUuid("17BFFC6C-A5DF-4198-ADAE-73D616A50009"), "My Region");
            _beaconRegion.NotifyOnEntry = true;
            _beaconRegion.NotifyOnExit = true;

            _beaconManager = new CLLocationManager();

            _beaconManager.AuthorizationChanged += BeaconManagerAuthorizationStatusChanged;
            _beaconManager.RegionEntered += BeaconManagerEnteredRegion;
            _beaconManager.RegionLeft += BeaconManagerExitedRegion;
            _beaconManager.RequestAlwaysAuthorization();

            return true;
        }
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

            var userNotificationSettings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert, new NSSet());
            UIApplication.SharedApplication.RegisterUserNotificationSettings(userNotificationSettings);

            _locationManager = new CLLocationManager();
            _locationManager.AuthorizationChanged += LocationManagerAuthorizationChanged;
            _locationManager.RegionEntered += LocationManagerRegionEntered;
            _locationManager.RegionLeft += LocationManagerRegionLeft;

            _locationManager.RequestAlwaysAuthorization();

            _region = new CLBeaconRegion(new NSUuid("18E1FDEA-15E6-425E-B88C-2642B8F3C378"), "MyRegion");

            return true;
        }
Ejemplo n.º 42
0
		public LocationManager ()
		{
			this.locMgr = new CLLocationManager();
			// iOS 8 has additional permissions requirements
			//
			if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
				locMgr.RequestAlwaysAuthorization (); // works in background
				//locMgr.RequestWhenInUseAuthorization (); // only in foreground
			}

			// iOS 9 requires the following for background location updates
			// By default this is set to false and will not allow background updates
			if (UIDevice.CurrentDevice.CheckSystemVersion (9, 0)) {
				locMgr.AllowsBackgroundLocationUpdates = true;
			}

			LocationUpdated += PrintLocation;

		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            Near = UIImage.FromBundle ("Images/square_near");
            Far = UIImage.FromBundle ("Images/square_far");
            Immediate = UIImage.FromBundle ("Images/square_immediate");
            Unknown = UIImage.FromBundle ("Images/square_unknown");

            beaconUUID = new NSUuid (uuid);
            beaconRegion = new CLBeaconRegion (beaconUUID, beaconMajor, beaconMinor, beaconId);

            beaconRegion.NotifyEntryStateOnDisplay = true;
            beaconRegion.NotifyOnEntry = true;
            beaconRegion.NotifyOnExit = true;

            locationmanager = new CLLocationManager ();
            locationmanager.RequestAlwaysAuthorization ();

            locationmanager.RegionEntered += (object sender, CLRegionEventArgs e) => {

                    var notification = new UILocalNotification () { AlertBody = "The Xamarin beacon is close by!" };
                    UIApplication.SharedApplication.CancelAllLocalNotifications();
                    UIApplication.SharedApplication.PresentLocationNotificationNow (notification);
            };

            locationmanager.DidRangeBeacons += (object sender, CLRegionBeaconsRangedEventArgs e) => {

                if (e.Beacons.Length > 0) {

                    CLBeacon beacon = e.Beacons [0];
                    //this.Title = beacon.Proximity.ToString() + " " +beacon.Major + "." + beacon.Minor;
                }

                dataSource.Beacons = e.Beacons;
                TableView.ReloadData();
            };

            locationmanager.StartMonitoring (beaconRegion);
            locationmanager.StartRangingBeacons (beaconRegion);

            TableView.Source = dataSource = new DataSource (this);
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			map.GetViewForAnnotation = (mapView, annotation) => {
				return new MKPinAnnotationView (annotation, string.Empty) {
					Draggable = true
				};
			};

			locationManager = new CLLocationManager {
				DistanceFilter = CLLocationDistance.FilterNone,
				DesiredAccuracy = CLLocation.AccuracyBest,
			};

			locationManager.LocationsUpdated += OnLocationsUpdated;

			locationManager.RequestAlwaysAuthorization ();
			locationManager.StartUpdatingLocation ();
		}
        public MasterViewController()
            : base("MasterViewController", null)
        {
            //Title = NSBundle.MainBundle.LocalizedString("Master", "iBeacons Everywhere");

            Near = UIImage.FromBundle("Images/square_near");
            Far = UIImage.FromBundle("Images/square_far");
            Immediate = UIImage.FromBundle("Images/square_immediate");
            Unknown = UIImage.FromBundle("Images/square_unknown");

            _locationManager = new CLLocationManager();
            _locationManager.RequestAlwaysAuthorization();

            _locationManager.DidRangeBeacons += (object sender, CLRegionBeaconsRangedEventArgs e) =>
            {
                _dataSource.Beacons = e.Beacons;
                TableView.ReloadData();
            };

            _beaconRegions = new List<CLBeaconRegion>();
        }
Ejemplo n.º 46
0
        static BeaconManager()
        {
            beaconRegions = new List<CLBeaconRegion> ();
            locationManager = new CLLocationManager ();

            locationManager.RegionEntered += HandleRegionEntered;
            locationManager.RegionLeft += HandleRegionLeft;
            locationManager.DidRangeBeacons += HandleDidRangeBeacons;
            locationManager.DidStartMonitoringForRegion += HandleDidStartMonitoringForRegion;
            locationManager.MonitoringFailed += HandleMonitoringFailed;
            locationManager.RangingBeaconsDidFailForRegion += HandleMonitoringFailed;

            locationManager.RequestAlwaysAuthorization ();

            if (CLLocationManager.Status == CLAuthorizationStatus.Denied) {
                HandleMonitoringFailed (null, new EventArgs ());
            }

            #if DEBUG
            //			RegisterBeaconRegion ("B9407F30-F5F8-466E-AFF9-25556B57FE6D", "Estimotes");
            //			RegisterBeaconRegion ("8492E75F-4FD6-469D-B132-043FE94921D8", "PhoneEstimotes");
            #endif
        }
Ejemplo n.º 47
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            MapServices.ProvideAPIKey ("AIzaSyA8WOvgGyHaw3rgkeYuUIqkIxhmW9Hrdjc");

            locationManager = new CLLocationManager ();
            locationManager.Delegate = new locationManagerDelegate ();
            locationManager.DesiredAccuracy = CLLocation.AccuracyBest;

            locationManager.RequestAlwaysAuthorization ();

            if (locationManager.RespondsToSelector (new Selector ("requestWhenInUseAuthorization")))
            {
                locationManager.RequestWhenInUseAuthorization ();
            }
            if (CLLocationManager.LocationServicesEnabled) {
                locationManager.StartUpdatingLocation ();
            }

            ProgressHUD.Shared.HudForegroundColor = UIColor.Gray;
            ProgressHUD.Shared.Ring.Color = UIColor.FromRGB(44/255f,146/255f,208/255f);
            ProgressHUD.Shared.HudForegroundColor = UIColor.FromRGB(44/255f,146/255f,208/255f);

            UIApplication.SharedApplication.SetStatusBarStyle (UIStatusBarStyle.LightContent, true);

            this.Window = new UIWindow (UIScreen.MainScreen.Bounds);
            UINavigationController navigation = new UINavigationController(new StartingScreen());
            navigation.NavigationBar.TintColor = UIColor.White;
            navigation.NavigationBar.BarTintColor = UIColor.FromRGB(44/255f,146/255f,208/255f);
            navigation.NavigationBar.BarStyle = UIBarStyle.Black;
            navigation.SetNavigationBarHidden (true,true);

            this.Window.RootViewController = navigation;
            this.Window.MakeKeyAndVisible ();

            return true;
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            CLCircularRegion region = new CLCircularRegion(new CLLocationCoordinate2D(10.009176843388, 76.3615990792536), 20.0, "Jubin's Desk");

            locLabel = (UILabel)this.View.ViewWithTag(2004);
            locLabel1 = (UILabel)this.View.ViewWithTag(2005);
            statusLabel = (UILabel)this.View.ViewWithTag(2006);
            locLabel.Text = "Location...";
            locManager = new CLLocationManager();
            locManager.RequestAlwaysAuthorization ();
            //locManager.RequestWhenInUseAuthorization ();
            locManager.DesiredAccuracy = CLLocation.AccuracyBest;
            //locManager.DistanceFilter = 5.0;
            locManager.UpdatedLocation+=(object sender, CLLocationUpdatedEventArgs e) => {
                locLabel.Text = "Longitude: "+e.NewLocation.Coordinate.Longitude+" Lattitude: "+e.NewLocation.Coordinate.Latitude;
                System.Diagnostics.Debug.WriteLine("Longitude: "+e.NewLocation.Coordinate.Longitude+" Lattitude: "+e.NewLocation.Coordinate.Latitude);
            };
            /* this gets fired and works fine */
            locManager.LocationsUpdated+=(object sender, CLLocationsUpdatedEventArgs e) => {
                foreach (CLLocation aLocation in e.Locations)
                {
                    locLabel1.Text = "Longitude: "+aLocation.Coordinate.Longitude.ToString()+" Lattitude: "+aLocation.Coordinate.Latitude.ToString();
                    if (region.ContainsCoordinate(new CLLocationCoordinate2D(aLocation.Coordinate.Latitude, aLocation.Coordinate.Longitude)))
                    {
                        statusLabel.Text = "Normal location update: cordinates inside the region";
                    }
                    else
                    {
                        statusLabel.Text = "Normal location update: cordinates outside the region";
                    }
                }
            };
            locManager.StartUpdatingLocation();

            if (CLLocationManager.IsMonitoringAvailable (typeof(CLCircularRegion)))
            {
                /* This doesn't get fired */
                locManager.DidDetermineState += (object sender, CLRegionStateDeterminedEventArgs e) => {
                    switch(e.State)
                    {
                        case CLRegionState.Inside:
                        InvokeOnMainThread(()=>{
                            locLabel.Text = "Iniside...";
                            UIAlertView testAlert = new UIAlertView ();
                            testAlert.AddButton ("OK");
                            testAlert.Title = "Entered";
                            testAlert.Message = "Region "+e.Region.ToString();
                            testAlert.Show();
                        });
                        break;

                        case CLRegionState.Outside:
                        InvokeOnMainThread(()=>{
                            locLabel.Text = "Outside...";
                            UIAlertView testAlert1 = new UIAlertView ();
                            testAlert1.AddButton ("OK");
                            testAlert1.Title = "Exit";
                            testAlert1.Message = "Region "+e.Region.ToString();
                            testAlert1.Show();
                        });
                        break;

                        case CLRegionState.Unknown:
                        InvokeOnMainThread(()=>{
                            locLabel.Text = "Unknown state for region...";
                        });
                        break;
                        default:
                        break;
                    }
                };
                /* This works and gets fired */
                locManager.DidStartMonitoringForRegion += (o, e) => {
                    InvokeOnMainThread(()=>{
                        locManager.RequestState(e.Region);
                        locLabel.Text = "Now monitoring region : "+ e.Region.ToString ();
                    });
                };
                /* This doesn't get fired */
                locManager.DidVisit+=(object sender, CLVisitedEventArgs e) => {
                    InvokeOnMainThread(()=>{
                        locLabel.Text = "Did visit region...";
                        UIAlertView testAlert = new UIAlertView ();
                        testAlert.AddButton ("OK");
                        testAlert.Title = "Visited";
                        testAlert.Message = "Region "+e.Visit.Coordinate.Latitude.ToString()+" | "+e.Visit.Coordinate.Longitude.ToString();
                        testAlert.Show();
                    });
                };
                /* This doesn't get fired */
                locManager.RegionEntered += (o, e) => {
                    InvokeOnMainThread(()=>{
                        UIAlertView testAlert = new UIAlertView ();
                        testAlert.AddButton ("OK");
                        testAlert.Title = "Entered";
                        testAlert.Message = "Region "+e.Region.ToString();
                        testAlert.Show();
                        locLabel.Text = "Entered: "+e.Region.ToString();
                    });
                };
                /* This doesn't get fired */
                locManager.RegionLeft += (o, e) => {
                    InvokeOnMainThread(()=>{
                        UIAlertView testAlert = new UIAlertView ();
                        testAlert.AddButton ("OK");
                        testAlert.Title = "Exit";
                        testAlert.Message = "Region "+e.Region.ToString();
                        testAlert.Show();
                        locLabel.Text = "Left: "+e.Region.ToString();
                    });
                };
                locManager.StartMonitoring (region);
            }
            else
            {
            }
            // Perform any additional setup after loading the view, typically from a nib.
        }
        void ShowActualLocationPermissionAlert()
        {
            _locationManager = new CLLocationManager ();
            _locationManager.Delegate = new LocationManagerDelegate (this);

            if (_locationAuthorizationType == ClusterLocationAuthorizationType.Always &&
                _locationManager.RespondsToSelector (new Selector ("requestAlwaysAuthorization")))
            {
                _locationManager.RequestAlwaysAuthorization ();
            }
            else if (_locationAuthorizationType == ClusterLocationAuthorizationType.WhenInUse &&
                     _locationManager.RespondsToSelector (new Selector ("requestWhenInUseAuthorization")))
            {
                _locationManager.RequestWhenInUseAuthorization ();
            }

            _locationManager.StartUpdatingLocation ();
        }
Ejemplo n.º 50
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			this.Add (faceBookView);
			this.Add (facebookView2);

			iPhoneLocationManager = new CLLocationManager ();
			iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;
			iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {

			};
				
			iPhoneLocationManager.RequestAlwaysAuthorization ();
			if (CLLocationManager.LocationServicesEnabled) {
				iPhoneLocationManager.StartUpdatingLocation ();
			}
			#region observadores del teclado
			// Keyboard popup
			NSNotificationCenter.DefaultCenter.AddObserver
			(UIKeyboard.DidShowNotification,KeyBoardUpNotification);

			// Keyboard Down
			NSNotificationCenter.DefaultCenter.AddObserver
			(UIKeyboard.WillHideNotification,KeyBoardDownNotification);
			#endregion

			#region declaracion de vista de Facebook
			// Create the Facebook LogIn View with the needed Permissions
			// https://developers.facebook.com/ios/login-ui-control/
			loginView = new FBLoginView (ExtendedPermissions) {
				Frame = new CGRect (0,0,45, 45)
			};

			// Create view that will display user's profile picture
			// https://developers.facebook.com/ios/profilepicture-ui-control/

			pictureView = new FBProfilePictureView () {
				Frame = new CGRect (0, 0, 45, 45)
			};
			pictureView.UserInteractionEnabled = true;
			// Hook up to FetchedUserInfo event, so you know when
			// you have the user information available
			loginView.FetchedUserInfo += (sender, e) => {
				user = e.User;
				pictureView.ProfileID = user.GetId ();
				MainView.isWithFacebook = true;
				loginView.Alpha = 0.1f;
				pictureView.Hidden = false;
			};

			// Clean user Picture and label when Logged Out
			loginView.ShowingLoggedOutUser += (sender, e) => {
				pictureView.ProfileID = null;
				pictureView.Hidden = true;
				lblUserName.Text = string.Empty;
				loginView.Alpha = 1f;
				MainView.isWithFacebook = false;
			};
		
			this.faceBookView.Add(pictureView);
			this.faceBookView.Add(loginView);
			#endregion

			var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			_pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

			//Creamos la base de datos y la tabla de persona
			using (var conn= new SQLite.SQLiteConnection(_pathToDatabase))
			{
				conn.CreateTable<Person>();
				conn.CreateTable<State> ();
				conn.CreateTable<Terms> ();
				conn.CreateTable<PrivacyNotice> ();
			}

			using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
			{
				people = new List<Person> (from p in db.Table<Person> () select p);
				states = new List<State> (from s in db.Table<State> () select s);
				terms = new List<Terms> (from t in db.Table<Terms> ()select t);
				privacyNotices = new List<PrivacyNotice> (from pr in db.Table<PrivacyNotice> () select pr);
			}

			if(people.Count > 0){
				Person user = people.ElementAt(0);
				MainView.userId = user.ID;
				Console.WriteLine ("El Id de usuario es: "+ user.ID);
			}

			if(states.Count > 0){
				State estado = states.ElementAt(0);
				MainView.localityId = estado.localityId;
				Console.WriteLine ("El Id de localidad es: "+ estado.stateId);
			}
				
			//Boton para entrar al menu de la aplicacion.
			this.btnEntrar.TouchUpInside += (sender, e) => {
				scanView = new ScanView();
				this.NavigationController.PushViewController(scanView, true);
			};

			this.btnListas.TouchUpInside += (sender, e) => {
				using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
				{
					people = new List<Person> (from p in db.Table<Person> () select p);
				}
				if(people.Count > 0){
					MyListsView mylists = new MyListsView();
					this.NavigationController.PushViewController(mylists,true);
				}else{
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes iniciar sesion para acceder a tus listas"
					};
					alert.AddButton ("Aceptar");
					alert.Show ();
				}
			};

			//Boton para hacer busqueda por nombre de producto
			this.btnBuscar.TouchUpInside += (sender, e) => {
				if(this.cmpNombre.Text == ""){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar"
					};
					alert.AddButton ("Aceptar");
					alert.Show ();
				}
				else if (states.Count < 1){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
							"Al menu de opciones para establecerla"
					};
					alert.AddButton ("Aceptar");
					alert.Clicked += (s, o) => {
						StatesView statesView = new StatesView();
						this.NavigationController.PushViewController(statesView, true);
					};
					alert.Show ();
				}
				else{
					this._loadPop = new LoadingOverlay (UIScreen.MainScreen.Bounds);
					this.View.Add ( this._loadPop );
					this.cmpNombre.ResignFirstResponder();
					Task.Factory.StartNew (
						() => {
							System.Threading.Thread.Sleep ( 1 * 1000 );
						}
					).ContinueWith ( 
						t => {
							nsr = new NameSearchResultView();
							nsr.setProductName(this.cmpNombre.Text.Trim());
							this.NavigationController.PushViewController(nsr,true);
							this._loadPop.Hide ();
						}, TaskScheduler.FromCurrentSynchronizationContext()
					);
				}
			};

			this.cmpNombre.ShouldReturn += (textField) => {
				if(this.cmpNombre.Text == ""){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar"
					};
					alert.AddButton ("Aceptar");
					alert.Show ();
				}
				else if (states.Count < 1){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
							"Al menu de opciones para establecerla"
					};
					alert.AddButton ("Aceptar");
					alert.Clicked += (s, o) => {
						StatesView statesView = new StatesView();
						this.NavigationController.PushViewController(statesView, true);
					};
					alert.Show ();
				}
				else{
					this._loadPop = new LoadingOverlay (UIScreen.MainScreen.Bounds);
					this.View.Add ( this._loadPop );
					this.cmpNombre.ResignFirstResponder();
					Task.Factory.StartNew (
						() => {
							System.Threading.Thread.Sleep ( 1 * 1000 );
						}
					).ContinueWith ( 
						t => {
							nsr = new NameSearchResultView();
							nsr.setProductName(this.cmpNombre.Text.Trim());
							this.NavigationController.PushViewController(nsr,true);
							this._loadPop.Hide ();
						}, TaskScheduler.FromCurrentSynchronizationContext()
					);
				} 
				return true; 
			};

			//Boton para iniciar el escaner de codigo de barras
			this.btnCodigo.TouchUpInside += (sender, e) => {
				if(states.Count > 0){
					// Configurar el escaner de codigo de barras.
					picker = new ScanditSDKRotatingBarcodePicker (appKey);
					picker.OverlayController.Delegate = new overlayControllerDelegate(picker, this);
					picker.OverlayController.ShowToolBar(true);
					picker.OverlayController.ShowSearchBar(true);
					picker.OverlayController.SetToolBarButtonCaption("Cancelar");
					picker.OverlayController.SetSearchBarKeyboardType(UIKeyboardType.Default);
					picker.OverlayController.SetSearchBarPlaceholderText("Búsqueda por nombre de producto");
					picker.OverlayController.SetCameraSwitchVisibility(SICameraSwitchVisibility.OnTablet);
					picker.OverlayController.SetTextForInitializingCamera("Iniciando la camara");
					this.PresentViewController (picker, true, null);
					picker.StartScanning ();
				}else{
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
							"Al menu de opciones para establecerla"
					};
					alert.AddButton ("Aceptar");
					alert.Clicked += (s, o) => {
						StatesView statesView = new StatesView();
						this.NavigationController.PushViewController(statesView, true);
					};
					alert.Show ();
				}
			};
		}
Ejemplo n.º 51
0
			public LocationManager(WoodCore core,ServiceArgs args){
				this.core=core;
				this.args=args;
				Id=Guid.NewGuid();
				mgr=new CLLocationManager();
				if(UIDevice.CurrentDevice.CheckSystemVersion(8,0)){
					mgr.RequestAlwaysAuthorization();
				}
				if(CLLocationManager.LocationServicesEnabled){
					mgr.DesiredAccuracy=1;
					//StartUpdatingLocation();
					mgr.LocationsUpdated+=delegate(object sender,CLLocationsUpdatedEventArgs e) {
						LocationUpdated(this,new LocationUpdatedEventArgs(e.Locations[e.Locations.Length-1]));	
					};
				}
			}
Ejemplo n.º 52
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            var locSvc = new ROMPLocation ();
            myFacilities = locSvc.GetLocations (sessionKey, groupID);
            locMan = new CLLocationManager ();

            if (myFacilities.Count () > 0) {
                if (!CLLocationManager.LocationServicesEnabled) {
                    UIAlertView _error = new UIAlertView ("Error", "Location services not enabled, please enable this in your Settings.", null, "Ok", null);
                    _error.Show ();
                } else if (CLLocationManager.Status == CLAuthorizationStatus.Denied) {
                    UIAlertView _error = new UIAlertView ("Error", "App is not authorized to use location data.", null, "Ok", null);
                    _error.Show ();
                } else {
                    //locMan.LocationUpdated += LocationChanged;
                    locMan.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;
                    if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
                        locMan.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                            UpdateLocation (e.Locations [e.Locations.Length - 1]);
                        };
                    } else {
                        #pragma warning disable 618
                        // this won't be called on iOS 6 (deprecated)
                        locMan.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
                            UpdateLocation (e.NewLocation);
                        };
                        #pragma warning restore 618
                    }

                    if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                    {
                        locMan.RequestAlwaysAuthorization ();
                    }

                    if (CLLocationManager.LocationServicesEnabled)
                        locMan.StartUpdatingLocation ();
                    if (CLLocationManager.HeadingAvailable)
                        locMan.StartUpdatingHeading ();
                }
                btnCheckIn.BackgroundColor = new UIColor(new CoreGraphics.CGColor(0.9f,0.9f,0.9f));
                btnCheckIn.Layer.CornerRadius = 1;
                btnCheckIn.TouchUpInside += (object sender, EventArgs e) => {
                    if (currentLocation != null) {
                        if (groupID <= 2) {
                            string absResult = "You Are Not Within A Specified Zone.";
                            string absTitle = "Error";
                            if (btnCheckIn.Title (UIControlState.Normal) == "Check In") {
                                foreach (FacilityCoordinates fc in myFacilities) {
                                    var fenceLat = fc.Latitude;
                                    var fenceLon = fc.Longitude;
                                    var R = 6371; // Radius of the earth in km
                                    var dLat = deg2rad (currentLocation.Coordinate.Latitude - fenceLat);  // deg2rad below
                                    var dLon = deg2rad (currentLocation.Coordinate.Longitude - fenceLon);
                                    var a =
                                        Math.Sin (dLat / 2) * Math.Sin (dLat / 2) +
                                        Math.Cos (deg2rad (fenceLat)) * Math.Cos (deg2rad (currentLocation.Coordinate.Latitude)) *
                                        Math.Sin (dLon / 2) * Math.Sin (dLon / 2);
                                    var c = 2 * Math.Atan2 (Math.Sqrt (a), Math.Sqrt (1 - a));
                                    var d = R * c;
                                    if (d <= 0.25) {
                                        string result = locSvc.CheckIn (sessionKey, fc.LocationID);
                                        if (result == "Success") {
                                            absTitle = "Success";
                                            absResult = "Check In Successful";
                                            btnCheckIn.SetTitle ("CHECK OUT", UIControlState.Normal);
                                            break;
                                        } else {
                                            absTitle = "Error";
                                            absResult = "An Unexpected Error Occurred. Try Again";
                                        }
                                    }
                                }
                            } else if (btnCheckIn.Title (UIControlState.Normal) == "Check Out") {
                                string result = locSvc.CheckOutWithoutLocation (sessionKey);
                                if (result == "Success") {
                                    absTitle = "Success";
                                    absResult = "Check Out Successful";
                                    btnCheckIn.SetTitle ("CHECK IN", UIControlState.Normal);
                                } else {
                                    absTitle = "Error";
                                    absResult = "An Unexpected Error Occurred. Try Again";
                                }
                            }
                            UIAlertView _error = new UIAlertView (absTitle, absResult, null, "Ok", null);
                            _error.Show ();
                        } else if (groupID > 2 && groupID <= 7) {
                            string absResult = "";
                            string absTitle = "";
                            if (btnCheckIn.Title (UIControlState.Normal) == "Check In") {
                                string result = locSvc.CheckInWithLocation (sessionKey, -1, currentLocation.Coordinate.Latitude, currentLocation.Coordinate.Longitude);
                                if (result == "Success") {
                                    absTitle = "Success";
                                    absResult = "Check In Successful";
                                    btnCheckIn.SetTitle ("CHECK OUT", UIControlState.Normal);
                                } else {
                                    absTitle = "Error";
                                    absResult = "An Unexpected Error Occurred. Try Again";
                                }
                            } else if (btnCheckIn.Title (UIControlState.Normal) == "Check Out") {
                                string result = locSvc.CheckOutWithoutLocation (sessionKey);
                                if (result == "Success") {
                                    absTitle = "Success";
                                    absResult = "Check In Successful";
                                    btnCheckIn.SetTitle ("CHECK IN", UIControlState.Normal);
                                } else {
                                    absTitle = "Error";
                                    absResult = "An Unexpected Error Occurred. Try Again";
                                }
                            }
                            UIAlertView _error = new UIAlertView (absTitle, absResult, null, "Ok", null);
                            _error.Show ();
                        } else if (groupID == 8) {
                            var fenceLat = 48.46003187;
                            var fenceLon = -89.18908003;
                            var R = 6371; // Radius of the earth in km
                            var dLat = deg2rad (currentLocation.Coordinate.Latitude - fenceLat);  // deg2rad below
                            var dLon = deg2rad (currentLocation.Coordinate.Longitude - fenceLon);
                            var a =
                                Math.Sin (dLat / 2) * Math.Sin (dLat / 2) +
                                Math.Cos (deg2rad (fenceLat)) * Math.Cos (deg2rad (currentLocation.Coordinate.Latitude)) *
                                Math.Sin (dLon / 2) * Math.Sin (dLon / 2);
                            var c = 2 * Math.Atan2 (Math.Sqrt (a), Math.Sqrt (1 - a));
                            var d = R * c;
                            string absResult = d.ToString ();
                            UIAlertView _error = new UIAlertView ("Check In", absResult, null, "Ok", null);
                            _error.Show ();
                        }
                    }
                };
            } else {
                btnCheckIn.Hidden = true;
                lblText.Text = "You have no locations to check in to. Please start the application during a rotation to properly utilize the functionality. Thank you.";
            }
            btnExit.BackgroundColor = new UIColor(new CoreGraphics.CGColor(0.9f,0.9f,0.9f));
            btnExit.Layer.CornerRadius = 1;
            btnExit.TouchUpInside += (object sender, EventArgs e) => {
                Environment.Exit(0);
            };
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            locationmanager = new CLLocationManager();

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                locationmanager.RequestAlwaysAuthorization();

            beaconUUID = new NSUuid(uuid);
            beaconRegion = new CLBeaconRegion(beaconUUID, beaconMajor, beaconMinor, beaconId);
            beaconRegion.NotifyEntryStateOnDisplay = true;
            beaconRegion.NotifyOnEntry = true;
            beaconRegion.NotifyOnExit = true;

            locationmanager.RegionEntered += (sender, e) =>
            {
                var notification = new UILocalNotification() { AlertBody = "The Xamarin beacon is close by!" };
                UIApplication.SharedApplication.CancelAllLocalNotifications();
                UIApplication.SharedApplication.PresentLocalNotificationNow(notification);

            };

            //create beacon region
            beaconUUID = new NSUuid(uuid);
            beaconRegion = new CLBeaconRegion(beaconUUID, beaconMajor, beaconMinor, beaconId);

            locationmanager.DidRangeBeacons += (object sender, CLRegionBeaconsRangedEventArgs e) =>
            {
                if (e.Beacons == null || e.Beacons.Length == 0)
                    return;

                LabelBeacon.Text = "We found: " + e.Beacons.Length + " beacons";

                var beacon = e.Beacons[0];

                switch (beacon.Proximity)
                {
                    case CLProximity.Far:
                        View.BackgroundColor = UIColor.Blue;
                        break;

                    case CLProximity.Near:
                        View.BackgroundColor = UIColor.Yellow;
                        break;

                    case CLProximity.Immediate:
                        View.BackgroundColor = UIColor.Green;
                        break;

                }

                LabelDistance.Text = "We are: " + beacon.Accuracy.ToString("##.000");

                if (beacon.Accuracy <= .1 && beacon.Proximity == CLProximity.Immediate)
                {
                    locationmanager.StopRangingBeacons(beaconRegion);
                    var vc = UIStoryboard.FromName("MainStoryboard", null).InstantiateViewController("FoundViewController");
                    NavigationController.PushViewController(vc, true);
                }

            };

            locationmanager.StartRangingBeacons(beaconRegion);
        }
Ejemplo n.º 54
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var documentDirectories = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true);
            string documentDirectory = documentDirectories[0];
            string path = Path.Combine(documentDirectory, "annotations.archive");
            Console.WriteLine("Path: {0}", path);

            var annotations = (NSMutableArray)NSKeyedUnarchiver.UnarchiveFile(path);
            if (annotations != null) {
                for (int i = 0; i < annotations.Count; i++) {
                    mapView.AddAnnotation(annotations.GetItem<BNRMapPoint>(i));
                }
            }

            // Perform any additional setup after loading the view, typically from a nib.
            //			locator = new Geolocator{ DesiredAccuracy = 50 };
            //
            //			locator.StartListening(5000, 1, false);
            //			locator.PositionChanged += (object sender, PositionEventArgs e) => {
            //				Console.WriteLine ("Position Status: {0}", e.Position.Accuracy);
            //				Console.WriteLine ("Position Latitude: {0}", e.Position.Latitude);
            //				Console.WriteLine ("Position Longitude: {0}", e.Position.Longitude);
            //			};
            //			locator.PositionError += (object sender, PositionErrorEventArgs e) => {
            //				Console.WriteLine("Could not find position: {0}, {1}", e.Error, e.ToString() );
            //			};

            var clm = new CLLocationManager();
            clm.RequestAlwaysAuthorization();

            actIndicator.StartAnimating();
            gettingLocLabel.Hidden = false;
            textField.Enabled = false;

            int mapTypeValue = NSUserDefaults.StandardUserDefaults.IntForKey(WhereamiMapTypePrefKey);

            segControl.SelectedSegment = mapTypeValue;

            mapView.MapType = (MKMapType)mapTypeValue;
            mapView.ShowsUserLocation = true;
            mapView.ZoomEnabled = true;

            CLLocationCoordinate2D  lastLoc = new CLLocationCoordinate2D(NSUserDefaults.StandardUserDefaults.DoubleForKey(WhereamiLastLocLatPrefKey),NSUserDefaults.StandardUserDefaults.DoubleForKey(WhereamiLastLocLongPrefKey));
            MKCoordinateRegion lastRegion = new MKCoordinateRegion(lastLoc, new MKCoordinateSpan(0.0025, 0.0025));
            mapView.SetRegion(lastRegion, true);

            //currLocation = new CLLocationCoordinate2D(20.7592, -156.4572);

            // C# style event handler - can access class instance variables
            mapView.DidUpdateUserLocation += (object sender, MKUserLocationEventArgs e) =>
            {
                actIndicator.StopAnimating();
                gettingLocLabel.Hidden = true;
                textField.Enabled = true;
                Console.WriteLine(".NET Lat: {0}, Long: {1}, Alt: {2}", e.UserLocation.Coordinate.Latitude, e.UserLocation.Coordinate.Longitude, e.UserLocation.Location.Altitude);
                currLocation = e.UserLocation.Coordinate;
                if (firstLaunch) {
                    mapView.SetRegion(MKCoordinateRegion.FromDistance(currLocation, 250, 250), true);
                    firstLaunch = false;
                }
                else
                    mapView.SetCenterCoordinate(currLocation, true);
            };

            mapView.DidFailToLocateUser += (object sender, NSErrorEventArgs e) => {
                Console.WriteLine("Could not find location: {0}", e.ToString());
                actIndicator.StartAnimating();
                gettingLocLabel.Hidden = false;
                textField.Enabled = false;
            };

            mapView.DidSelectAnnotationView += (object sender, MKAnnotationViewEventArgs e) =>
            {
                var annotation = e.View.Annotation as BNRMapPoint;

                if (annotation != null) {
                    Console.WriteLine(".NET DidSelectAnnotationView: {0}", annotation.Title);
                }

            };

            // Strong Delegate method. Create delegate class as nested class of ViewCOntroller
            // Override need methods in that nested delegate class
            //			mapDelegate = new WhereAmIMapDelegate();
            //			mapView.Delegate = mapDelegate;

            // Weak delegate method. use Export attribute with selector to override then implement method.
            // Whichever is assigned last wins and kills the other.
            //			mapView.WeakDelegate =  this;

            //			textField.Delegate = new TextFieldDelegate();

            textField.EditingDidEndOnExit += (object sender, EventArgs e) =>
            {
                actIndicator.Hidden = false;
                if (!firstLaunch) {
                    BNRMapPoint mp = new BNRMapPoint(textField.Text, currLocation);

                    NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Latitude, WhereamiLastLocLatPrefKey);
                    NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Longitude, WhereamiLastLocLongPrefKey);

                    mapView.AddAnnotation(mp);
                    textField.ResignFirstResponder();
                    textField.Text = "";
                    actIndicator.Hidden = true;
                }
                else {
                    var locator = new Geolocator{ DesiredAccuracy = 50 };
                    locator.GetPositionAsync (timeout: 10000).ContinueWith (t => {
                        CLLocationCoordinate2D coord = new CLLocationCoordinate2D(t.Result.Latitude, t.Result.Longitude);
                        currLocation = coord;
                        MKCoordinateRegion region = MKCoordinateRegion.FromDistance(currLocation, 250, 250);
                        mapView.SetRegion(region, true);
                        BNRMapPoint mp = new BNRMapPoint(textField.Text, currLocation);

                        NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Latitude, WhereamiLastLocLatPrefKey);
                        NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Longitude, WhereamiLastLocLongPrefKey);

                        mapView.AddAnnotation(mp);
                        textField.ResignFirstResponder();
                        textField.Text = "";
                        actIndicator.Hidden = true;
                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }

            };

            segControl.BackgroundColor = UIColor.White;
            segControl.ValueChanged += (object sender, EventArgs e) =>
            {
                NSUserDefaults.StandardUserDefaults.SetInt(segControl.SelectedSegment, WhereamiMapTypePrefKey);

                switch (segControl.SelectedSegment)
                {
                    case 0:
                        mapView.MapType = MKMapType.Standard;
                        break;
                    case 1:
                        mapView.MapType = MKMapType.Satellite;
                        break;
                    case 2:
                        mapView.MapType = MKMapType.Hybrid;
                        break;
                    default:
                        break;

                }
            };
        }
Ejemplo n.º 55
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Perform any additional setup after loading the view, typically from a nib.
            //			locator = new Geolocator{ DesiredAccuracy = 50 };
            //
            //			locator.StartListening(5000, 1, false);
            //			locator.PositionChanged += (object sender, PositionEventArgs e) => {
            //				Console.WriteLine ("Position Status: {0}", e.Position.Accuracy);
            //				Console.WriteLine ("Position Latitude: {0}", e.Position.Latitude);
            //				Console.WriteLine ("Position Longitude: {0}", e.Position.Longitude);
            //			};
            //			locator.PositionError += (object sender, PositionErrorEventArgs e) => {
            //				Console.WriteLine("Could not find position: {0}, {1}", e.Error, e.ToString() );
            //			};

            actIndicator.Hidden = true;
            mapView.MapType = MKMapType.Standard;

            var clm = new CLLocationManager();
            clm.RequestAlwaysAuthorization();

            mapView.ShowsUserLocation = true;

            //currLocation = new CLLocationCoordinate2D(20.7592, -156.4572);

            // C# style event handler - can access class instance variables
            mapView.DidUpdateUserLocation += (object sender, MKUserLocationEventArgs e) =>
            {
                Console.WriteLine(".NET Lat: {0}, Long: {1}, Alt: {2}", e.UserLocation.Coordinate.Latitude, e.UserLocation.Coordinate.Longitude, e.UserLocation.Location.Altitude);
                currLocation = e.UserLocation.Coordinate;
                if (firstLaunch) {
                    mapView.SetRegion(MKCoordinateRegion.FromDistance(currLocation, 250, 250), true);
                    firstLaunch = false;
                }
                else
                    mapView.SetCenterCoordinate(currLocation, true);
            };

            mapView.DidSelectAnnotationView += (object sender, MKAnnotationViewEventArgs e) =>
            {
                var annotation = e.View.Annotation as BNRMapPoint;

                if (annotation != null) {
                    Console.WriteLine(".NET DidSelectAnnotationView: {0}", annotation.Title);
                }

            };

            // Strong Delegate method. Create delegate class as nested class of ViewCOntroller
            // Override need methods in that nested delegate class
            //			mapDelegate = new WhereAmIMapDelegate();
            //			mapView.Delegate = mapDelegate;

            // Weak delegate method. use Export attribute with selector to override then implement method.
            // Whichever is assigned last wins and kills the other.
            //			mapView.WeakDelegate =  this;

            //			textField.Delegate = new TextFieldDelegate();

            textField.EditingDidEndOnExit += (object sender, EventArgs e) =>
            {
                actIndicator.Hidden = false;
                if (!firstLaunch) {
                    BNRMapPoint mp = new BNRMapPoint(textField.Text, currLocation);
                    mapView.AddAnnotation(mp);
                    textField.ResignFirstResponder();
                    textField.Text = "";
                    actIndicator.Hidden = true;
                }
                else {
                    var locator = new Geolocator{ DesiredAccuracy = 50 };
                    locator.GetPositionAsync (timeout: 10000).ContinueWith (t => {
                        CLLocationCoordinate2D coord = new CLLocationCoordinate2D(t.Result.Latitude, t.Result.Longitude);
                        currLocation = coord;
                        MKCoordinateRegion region = MKCoordinateRegion.FromDistance(currLocation, 250, 250);
                        mapView.SetRegion(region, true);
                        BNRMapPoint mp = new BNRMapPoint(textField.Text, currLocation);
                        mapView.AddAnnotation(mp);
                        textField.ResignFirstResponder();
                        textField.Text = "";
                        actIndicator.Hidden = true;
                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }

            };

            segControl.BackgroundColor = UIColor.White;
            segControl.ValueChanged += (object sender, EventArgs e) =>
            {
                switch (segControl.SelectedSegment)
                {
                    case 0:
                        mapView.MapType = MKMapType.Standard;
                        break;
                    case 1:
                        mapView.MapType = MKMapType.Satellite;
                        break;
                    case 2:
                        mapView.MapType = MKMapType.Hybrid;
                        break;
                    default:
                        break;

                }
            };
        }
Ejemplo n.º 56
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			try{
			mapView = new MKMapView(View.Bounds);	
			mapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
			View.AddSubview(mapView);
			
			//Verificar si el dispositivo es un ipad o un iphone para cargar la tabla correspondiente a cada dispositivo
			if(UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone){
				Title= "Tiendas";
				tiendaCercana = new UIBarButtonItem (UIBarButtonSystemItem.Search);
				tiendaCercana.Target = this;
				this.NavigationItem.RightBarButtonItem = tiendaCercana;
			}else {
				Title = "Tiendas registradas";
				//Creamos el boton para buscar la tienda mas cercana.
				tiendaCercana = new UIBarButtonItem();
				tiendaCercana.Style = UIBarButtonItemStyle.Plain;
				tiendaCercana.Target = this;
				tiendaCercana.Title = "Buscar tienda cercana";
				this.NavigationItem.RightBarButtonItem = tiendaCercana;
			}
	
			//inicializacion del manejador de localizacion.
			iPhoneLocationManager = new CLLocationManager ();
			//Establecer la precision del manejador de localizacion.
			iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

			iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
				newLocation = e.Locations [e.Locations.Length - 1];
			};

		    List<StoresService> tiendas = storesService.All ();

			//mostramos los puntos rojos sobre cada una de las tiendas registradas.
			foreach (StoresService tienda in tiendas) {
					Console.WriteLine(tienda.nombre +" " + tienda.latitud + " "+tienda.longitud);
				double distancia1 = iPhoneLocationManager.Location.DistanceFrom(new CLLocation(Double.Parse(tienda.latitud),Double.Parse(tienda.longitud)))/1000;
				var annotation = new BasicMapAnnotation (new CLLocationCoordinate2D (Double.Parse(tienda.latitud), Double.Parse(tienda.longitud)), ""+tienda.nombre+" ("+Math.Round(distancia1,2)+"km)", ""+tienda.direccion);
				mapView.AddAnnotation (annotation);			
			}

			//Mostramos la ubicacion del usuario.
			mapView.ShowsUserLocation = true;
			MKUserLocation usr = mapView.UserLocation;
			usr.Title = "Tú estas aqui";
			
			// establecemos la region a mostrar, poniendo a Chihuahua como region
			var coords = new CLLocationCoordinate2D(28.6352778, -106.08888890000003); // Chihuahua
			var span = new MKCoordinateSpan(MilesToLatitudeDegrees (10), MilesToLongitudeDegrees (10, coords.Latitude));

			// se establece la region.
			mapView.Region = new MKCoordinateRegion (coords, span);

			//Mostrar los diferentes tipos de mapas
			int typesWidth=260, typesHeight=30, distanceFromBottom=60;
			mapTypes = new UISegmentedControl(new CGRect((View.Bounds.Width-typesWidth)/2, View.Bounds.Height-distanceFromBottom, typesWidth, typesHeight));
			mapTypes.InsertSegment("Mapa", 0, false);
			mapTypes.InsertSegment("Satelite", 1, false);
			mapTypes.InsertSegment("Ambos", 2, false);
			mapTypes.SelectedSegment = 0; // Road is the default
			mapTypes.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin;
			mapTypes.ValueChanged += (s, e) => {
				switch(mapTypes.SelectedSegment) {
				case 0:
					mapView.MapType = MKMapType.Standard;
					break;
				case 1:
					mapView.MapType = MKMapType.Satellite;
					break;
				case 2:
					mapView.MapType = MKMapType.Hybrid;
					break;
				}
			};
			View.AddSubview(mapTypes);


			//Añadimos el evento para buscar tienda mas cercana.
			tiendaCercana.Clicked += (sender, e) => {
				try{
					StoresService tiendac= nearestStore(newLocation,tiendas);
					double distancia = newLocation.DistanceFrom(new CLLocation(Double.Parse(tiendac.latitud),Double.Parse(tiendac.longitud)))/1000;
					UIAlertView alert = new UIAlertView () { 
							Title = "Tu tienda mas cercana es:", Message = ""+ tiendac.nombre + "\n "+ tiendac.direccion+"\n"+"Distancia: " + Math.Round(distancia,2) +"km"
					};
					alert.AddButton("Aceptar");
					alert.Show ();

					var coords1 = new CLLocationCoordinate2D(Double.Parse(tiendac.latitud), Double.Parse(tiendac.longitud));
					var span1 = new MKCoordinateSpan(MilesToLatitudeDegrees (0.2), MilesToLongitudeDegrees (0.2, coords.Latitude));

					// set the coords and zoom on the map
					mapView.Region = new MKCoordinateRegion (coords1, span1);
				}catch(Exception){
					UIAlertView alert = new UIAlertView () { 
						Title = "Ups =(", Message = "Algo salio mal, por favor intentalo de nuevo."
					};
					alert.AddButton("Aceptar");
					alert.Show ();
				}
			};  

			// Manejamos la actualizacion de la localizacion del dispositivo.
			iPhoneLocationManager.RequestAlwaysAuthorization ();
			if (CLLocationManager.LocationServicesEnabled)
				iPhoneLocationManager.StartUpdatingLocation ();

			} catch(System.Net.WebException){
				UIAlertView alert = new UIAlertView () { 
					Title = "Ups =(", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo."
				};
				alert.AddButton("Aceptar");
				alert.Show ();
			} catch(Exception){
				UIAlertView alert = new UIAlertView () { 
					Title = "Ups =(", Message = "Algo salio mal, por favor intentalo de nuevo."
				};
				alert.AddButton("Aceptar");
				alert.Show ();
			}
		}
Ejemplo n.º 57
-1
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			try{
				var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
				_pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

				using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
				{
					people = new List<Person> (from p in db.Table<Person> () select p);
				}

				//inicializacion del manejador de localizacion.
				iPhoneLocationManager = new CLLocationManager ();
				//Establecer la precision del manejador de localizacion.
				iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

				iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
					newLocation = e.Locations [e.Locations.Length - 1];
				};
					
				productSearchDetailService.setProductBarcode (this.barcode, MainView.localityId.ToString(), MainView.userId);
				List<ProductSearchDetailService> tableItems = productSearchDetailService.All ();

				this.productImages.Clear();
				foreach (var v in tableItems){
					Images image = new Images{ storeImageUrl = v.imagen};
					this.productImages.Add(image);
				}

				UIBarButtonItem home = new UIBarButtonItem();
				home.Style = UIBarButtonItemStyle.Plain;
				home.Target = this;
				home.Image = UIImage.FromFile("Images/home.png");
				this.NavigationItem.RightBarButtonItem = home;
				UIViewController[] vistas = NavigationController.ViewControllers;
				home.Clicked += (sender, e) => {
					this.NavigationController.PopToViewController(vistas[0], true);
				};

				btnTiendaCercana.TouchUpInside += (sender, e) => {
					try{
						ProductSearchDetailService tiendac= nearestStore(newLocation,tableItems);
						double distancia = newLocation.DistanceFrom(new CLLocation(Double.Parse(tiendac.tienda_latitud),Double.Parse(tiendac.tienda_longitud)))/1000;
						distancia = Math.Round(distancia,2);
						UIAlertView alert = new UIAlertView () { 
							Title = "Tu tienda mas cercana es:", Message = ""+ tiendac.tienda_nombre + "\n "+ tiendac.tienda_direccion+"\n"+"Distancia: " + distancia.ToString() +"km"
						};
						alert.AddButton("Aceptar");
						alert.AddButton("Mapa");
						alert.Clicked += (s , o) => {
							if(o.ButtonIndex == 1){
								SecondMapViewController mapView = new SecondMapViewController();
								mapView.setTienda(tiendac);
								this.NavigationController.PushViewController(mapView, true);
							}
						};
						alert.Show ();
					}catch(NullReferenceException){
						UIAlertView alert = new UIAlertView () { 
							Title = "Lo Sentimos =(", Message = "FixBuy no pudo obtener tu ubicación por favor ve a Ajustes/Privacidad/Localizacion y verifica que Fixbuy tenga permiso de saber tu ubicación"
						};
						alert.AddButton("Aceptar");
						alert.Show();
					}
				};  

				if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) {
					if (CLLocationManager.LocationServicesEnabled){
						this.tblStores.Source = new StoresTableSourceIphone (tableItems, this, iPhoneLocationManager,people.Count);
					}else{
						this.tblStores.Source = new StoresTableSourceIphone (tableItems, this, null,people.Count);
					}
				} else {
					if (CLLocationManager.LocationServicesEnabled){
						this.tblStores.Source = new StoresTableSource (tableItems, this, iPhoneLocationManager,people.Count);
					}else{
						this.tblStores.Source = new StoresTableSource (tableItems, this, null,people.Count);
					}
				}

				ProductSearchDetailService product = tableItems.ElementAt (0);
				NSUrl nsUrl = new NSUrl (product.imagen);
				NSData data = NSData.FromUrl (nsUrl);
				if(data!=null){
					this.imgProduct.Image = UIImage.LoadFromData (data);
				}else{
					this.imgProduct.Image = Images.sinImagen;
				}
				this.lblproduct.Text = product.nombre;
				this.lblDescription.Text = product.descripcion;
				//this.tblStores.TableHeaderView = this.headerView;
				Add (this.tblStores);

				// Manejamos la actualizacion de la localizacion del dispositivo.
				iPhoneLocationManager.RequestAlwaysAuthorization ();
				if (CLLocationManager.LocationServicesEnabled)
					iPhoneLocationManager.StartUpdatingLocation ();


			}catch(System.ArgumentOutOfRangeException){
				didNotFidProduct();
			}catch(Exception ex){
				Console.WriteLine ("ESTA ES LA EXCEPCION: " + ex.ToString ());
				this.imgProduct.Image = UIImage.FromFile("Images/noImage.jpg");
				this.lblproduct.Text = "Producto no encontrado =S";
				this.lblDescription.Text = "";
				this.btnTiendaCercana.Hidden = true;
				this.tblStores.BackgroundColor = UIColor.Clear;
				UIAlertView alert = new UIAlertView () { 
					Title = "Ups =(", Message = "Lo sentimos algo salio mal, por favor intentalo de nuevo"
				};
				alert.AddButton ("Aceptar");
				alert.Show ();
			} 
		}