2013-09-27 18 views
5

我有一個請求訪問Addressbook的問題,因爲ABAddressbook.Create始終爲空。Xamarin ios:ABAddressbook.Create始終爲空,無法請求訪問

那麼我該如何請求訪問?

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

感謝您的幫助。

+0

NSError err = new NSError(); (ABAddressBook ab = ABAddressBook.Create(out err))ab.RequestAccess(delegate {}); } //在使用後使用,什麼時候? :( – anguish

+0

是否在err中獲得值? – Jason

+0

是「ABAddressBookErrorDomain錯誤1.」 – anguish

回答

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 
} 
+0

得到了「ABAddressBookErrorDomain錯誤1.」錯誤 – anguish

+1

從Apple doc - >'kABOperationNotPermittedByUserError'。是否可能應用程序已被拒絕訪問設備用戶?如果是這樣,請檢查您的設置以重新啓用它 – poupou

+0

是的,一旦我找到了,我回答了沒有測試,但是如果我刪除應用程序,他總是記得我的決定嗎? – anguish

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

一些更好的錯誤處理是有保證的,但這取決於你想如何處理它。 – macawm