當應用程序加載時,將提示用戶啓用位置權限。只有當用戶在該彈出窗口中點擊「允許」或「不允許」時,我纔想移至下一頁。
在你ViewDidLoad
方法,你可以做這樣的事情:
// showTrackingMap is a class level var
showTrackingMap = new LocationCheck((s, ev) =>
{
if ((ev as LocationCheck.LocationCheckEventArgs).Allowed)
Console.WriteLine("Present Tracking Map ViewController");
else
Console.WriteLine("Disable Tracking Map");
showTrackingMap.Dispose();
});
LocationCheck
封裝位置請求,一旦用戶接受始終,只有在應用程序或拒絕位置隱私請求EventHandler
將觸發。
注意:EventHandler
也將被調用,如果用戶被指示去Setting
將應用程序從先前被拒絕更改爲允許(始終/應用程序在使用)。
public class LocationCheck : NSObject, ICLLocationManagerDelegate
{
public class LocationCheckEventArgs : EventArgs
{
public readonly bool Allowed;
public LocationCheckEventArgs(bool Allowed)
{
this.Allowed = Allowed;
}
}
CLLocationManager locationManager;
EventHandler locationStatus;
public LocationCheck(EventHandler locationStatus)
{
this.locationStatus = locationStatus;
Initialize();
}
public LocationCheck(NSObjectFlag x) : base(x) { Initialize(); }
public LocationCheck(IntPtr handle) : base(handle) { Initialize(); }
public LocationCheck(IntPtr handle, bool alloced) : base(handle, alloced) { Initialize(); }
public void Initialize()
{
locationManager = new CLLocationManager
{
Delegate = this
};
locationManager.RequestAlwaysAuthorization();
}
[Export("locationManager:didChangeAuthorizationStatus:")]
public void AuthorizationChanged(CLLocationManager manager, CLAuthorizationStatus status)
{
switch (status)
{
case CLAuthorizationStatus.AuthorizedAlways:
case CLAuthorizationStatus.AuthorizedWhenInUse:
locationStatus.Invoke(locationManager, new LocationCheckEventArgs(true));
break;
case CLAuthorizationStatus.Denied:
case CLAuthorizationStatus.Restricted:
locationStatus.Invoke(locationManager, new LocationCheckEventArgs(false));
break;
}
}
protected override void Dispose(bool disposing)
{
locationStatus = null;
locationManager.Delegate = null;
locationManager.Dispose();
base.Dispose(disposing);
}
}
謝謝。這正是我正在尋找的。 – TheDeveloper
@TheDeveloper NP,很高興它有幫助。 – SushiHangover