Xamarin ios: ABAddressbook.Create 始终为空,无法请求访问
本文关键字:访问 请求 ios ABAddressbook Create Xamarin | 更新日期: 2023-09-27 18:32:57
我在请求访问地址簿时遇到问题,因为ABAddressbook.Create总是为空。
那么我该如何请求访问权限呢?
NSError err = new NSError ();
ABAddressBook ab = ABAddressBook.Create(out err)
ab.RequestAccess (delegate {}); //ab always null
感谢您的帮助。
如果是null
,那么出了点问题,你的NSError
应该告诉你它是什么(顺便说一句,没有必要初始化out
参数)。
一般来说(iOS6+),你的代码应该看起来像:
NSError err;
var ab = ABAddressBook.Create (out err);
if (err != null) {
// process error
return;
}
// if the app was not authorized then we need to ask permission
if (ABAddressBook.GetAuthorizationStatus () != ABAuthorizationStatus.Authorized) {
ab.RequestAccess (delegate (bool granted, NSError error) {
if (error != null) {
// process error
} else if (granted) {
// permission now granted -> use the address book
}
});
} else {
// permission already granted -> use the address book
}
这是我处理这种情况的公式。
private void RequestAddressBookAccess ()
{
NSError error;
ABAddressBook addressBook = ABAddressBook.Create (out error);
if (error != null || addressBook == null)
ShowAddressBookAccessInstructions ();
else if (ABAddressBook.GetAuthorizationStatus () != ABAuthorizationStatus.Authorized) {
addressBook.RequestAccess (delegate(bool granted, NSError err) {
if (granted && err == null)
this.InvokeOnMainThread (() => DoStuff (addressBook));
else
ShowAddressBookAccessInstructions ();
});
} else
DoStuff (addressBook);
}
private void ShowAddressBookAccessInstructions ()
{
UIAlertView alert = new UIAlertView ("Cannot Access Contacts",
"Go to Settings -> Privacy -> Contacts and allow this app to access your contacts to use this functionality",
null, "Ok", null);
alert.Show();
}