Xamarin ios:ABAddressbook.Create始终为null,无法请求访问

时间:2013-09-27 08:30:34

标签: c# ios xamarin.ios xamarin abaddressbook

我在请求访问Addressbook时遇到问题,因为ABAddressbook.Create始终为null。

那么我该如何申请Access?

NSError err = new NSError ();
ABAddressBook ab = ABAddressBook.Create(out err)
ab.RequestAccess (delegate {}); //ab always null

感谢您的帮助。

2 个答案:

答案 0 :(得分:6)

如果是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
} 

答案 1 :(得分:0)

这是我处理这种情况的公式。

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();
}