我有一個請求訪問Addressbook的問題,因爲ABAddressbook.Create始終爲空。Xamarin ios:ABAddressbook.Create始終爲空,無法請求訪問
那麼我該如何請求訪問?
NSError err = new NSError();
ABAddressBook ab = ABAddressBook.Create(out err)
ab.RequestAccess (delegate {}); //ab always null
感謝您的幫助。
我有一個請求訪問Addressbook的問題,因爲ABAddressbook.Create始終爲空。Xamarin ios: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();
}
一些更好的錯誤處理是有保證的,但這取決於你想如何處理它。 – macawm
NSError err = new NSError(); (ABAddressBook ab = ABAddressBook.Create(out err))ab.RequestAccess(delegate {}); } //在使用後使用,什麼時候? :( – anguish
是否在err中獲得值? – Jason
是「ABAddressBookErrorDomain錯誤1.」 – anguish