2013-10-12 134 views
12

我正在將所有本地通訊錄聯繫人導入到我的應用中。目前,要求獲得「允許訪問聯繫人」權限的alertview是在應用程序啓動時完成的。請求允許訪問聯繫人iOS

如何更改它,以便在應用程序中的其他位置詢問權限?點擊一個按鈕,就像Instagram一樣?

看到這張照片:

enter image description here

+0

檢查[以編程方式請求訪問聯繫人](http://stackoverflow.com/questions/12648244/programmatically-request-access-to-contacts) –

+0

iOS 9及以上版本:http://stackoverflow.com/a/ 39374916/569789 – Zaraki

回答

22

您可以閱讀文檔HERE

下面是一些代碼,讓你開始:

//First of all import the AddRessBookUI 
    #import <AddressBookUI/AddressBookUI.h> 

    // Request to authorise the app to use addressbook 
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(nil, nil); 

    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) { 
    ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) { 
     if (granted) { 
      // If the app is authorized to access the first time then add the contact 
      [self _addContactToAddressBook]; 
     } else { 
      // Show an alert here if user denies access telling that the contact cannot be added because you didn't allow it to access the contacts 
     } 
    }); 
    } 
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) { 
    // If the user user has earlier provided the access, then add the contact 
    [self _addContactToAddressBook]; 
    } 
    else { 
    // If the user user has NOT earlier provided the access, create an alert to tell the user to go to Settings app and allow access 
    } 

這裏有另一對夫婦,你可能會喜歡看,你可以找到HEREHERE教程。

希望這會有所幫助!

UPDATE:必須使用didFinishLaunchingWithOptions以在第一時間檢測您的應用程序啓動:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"]) 
    { 
     // The app has already launched once 
    } 
    else 
    { 
     [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"]; 
     [[NSUserDefaults standardUserDefaults] synchronize]; 
     // This is the first time the app is launched 
    } 
} 
+0

很酷,如何在應用程序啓動時阻止應用程序訪問? – Hassan

+0

@Hassan檢查我的更新,瞭解如何檢測您的應用第一次啓動。在其他部分,你可以編寫一些代碼來不要求訪問聯繫人。 – AJ112

+0

真的幫了我!感謝球員 –

0

應用程序要求的權限當您嘗試retrive接觸。

只是在觸摸按鈕後調用重試,而不是在啓動後調用。

+0

是否有一個方法,當它要求權限時命中? – Hassan