我在请求访问地址簿时遇到问题,因为 ABAddressbook.Create 始终为空。
那么如何请求访问权限?
NSError err = new NSError ();
ABAddressBook ab = ABAddressBook.Create(out err)
ab.RequestAccess (delegate {}); //ab always null
感谢帮助。
我在请求访问地址簿时遇到问题,因为 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();
}