1. 程式人生 > >iOS開發之Accounts框架詳解

iOS開發之Accounts框架詳解

iOS開發之Accounts框架詳解

    Accounts框架是iOS原生提供的一套賬戶管理框架,其支援Facebook,新浪微博,騰訊微博,Twitter和領英賬戶管理的功能。需要注意,在iOS 11及以上系統中,將此功能已經刪除,因此Accounts.framework實際上已經沒有太大的意義,其只在iOS 11之前的系統上可用。

一、Accounts框架概覽

從上圖可以看出,Accounts框架中最重要的3個類是ACAccountCredential類、ACAccount類和ACAccountStore類。後面我們著重介紹這3個類。

      首先先來看ACAccountType類,這個類用來定義賬戶型別,如下:

@interface ACAccountType : NSObject
//型別描述
@property (readonly, nonatomic) NSString *accountTypeDescription;
//識別符號
@property (readonly, nonatomic) NSString *identifier;
//此類賬戶是否已經授權
@property (readonly, nonatomic) BOOL     accessGranted;
@end

需要注意,這個類中的屬性都是隻讀的,這也就是說,開發者不能夠直接使用這個類進行物件的構建,需要藉助ACAccountStore類來建立ACAccountType例項,後面會介紹。

      ACErrorCode定義了錯誤碼的意義,如下:

typedef enum ACErrorCode {
    ACErrorUnknown = 1,//未知錯誤
    ACErrorAccountMissingRequiredProperty,  // 缺少必選屬性錯誤
    ACErrorAccountAuthenticationFailed,     // 授權失敗
    ACErrorAccountTypeInvalid,              // 授權無效
    ACErrorAccountAlreadyExists,            // 賬戶已經存在
    ACErrorAccountNotFound,                 // 賬戶未找到
    ACErrorPermissionDenied,                // 沒有許可權
    ACErrorAccessInfoInvalid,               // 資訊失效
    ACErrorClientPermissionDenied,          // 客戶端沒有許可權
    ACErrorAccessDeniedByProtectionPolicy,  // 無法取得證書
    ACErrorCredentialNotFound,              // 證書未找到
    ACErrorFetchCredentialFailed,           // 請求證書失敗
    ACErrorStoreCredentialFailed,           // 儲存證書失敗
    ACErrorRemoveCredentialFailed,          // 刪除證書失敗
    ACErrorUpdatingNonexistentAccount,      // 更新失敗
    ACErrorInvalidClientBundleID,           // 無效的BundleID
    ACErrorDeniedByPlugin,                  // 許可權被阻止
    ACErrorCoreDataSaveFailed,              // 資料庫儲存失敗
    ACErrorFailedSerializingAccountInfo,    //序列化資料失敗
    ACErrorInvalidCommand,                  //無效的命令
    ACErrorMissingTransportMessageID,       //缺少安全資訊
    ACErrorCredentialItemNotFound,          // 證書缺少欄位
    ACErrorCredentialItemNotExpired,        // 證書欄位失效
} ACErrorCode;

二、進行賬戶操作

    在iOS 11以下的系統中,在設定中可以找到賬戶管理選項,如下圖:

點選相應的社交平臺,通過賬號密碼可以進行登入。這裡一旦設定登入,那麼在第三方應用程式中便可以通過Accounts框架來獲取授權資訊。

    首先,要使用Accounts框架,需要匯入相應標頭檔案,如下:

#import <Accounts/Accounts.h>

但應用程式首次使用使用者社交平臺的賬戶時,需要獲取使用者的授權,示例程式碼如下:

//建立操作物件
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
//通過操作物件 構建社交平臺型別示例  這裡採用的新浪微博
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierSinaWeibo];
//進行使用者授權請求
[accountStore requestAccessToAccountsWithType: accountType options:nil completion:^(BOOL granted, NSError *error) {
   if (error) {
        NSLog(@"error = %@", [error localizedDescription]);
   }      
   dispatch_async(dispatch_get_main_queue(), ^{
      if(granted){
         NSLog(@"授權通過了");
    });
}];

獲取使用者授權介面如下圖所示:

一旦使用者授權通過,可以使用如下方法獲取到使用者的社交平臺賬戶資訊:

ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierSinaWeibo];
NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];

Accounts框架支援的社交平臺型別ID如下:

NSString * const ACAccountTypeIdentifierTwitter;//Twitter
NSString * const ACAccountTypeIdentifierFacebook;//Facebook
NSString * const ACAccountTypeIdentifierSinaWeibo;//新浪微博
NSString * const ACAccountTypeIdentifierTencentWeibo;//騰訊微博
NSString * const ACAccountTypeIdentifierLinkedIn;//領英

在呼叫requestAccessToAccountsWithType方法時,可以傳入一個字典引數,某些社交平臺的授權需要配置一些額外引數,例如:

//facebook相關
NSString * const ACFacebookAppIdKey;//設定appid
NSString * const ACFacebookPermissionsKey;//設定許可權key
NSString * const ACFacebookAudienceKey; //許可權key
NSString * const ACFacebookAudienceEveryone;//公開許可權
NSString * const ACFacebookAudienceFriends;//好友許可權
NSString * const ACFacebookAudienceOnlyMe;//私人許可權
//領英相關
NSString * const ACLinkedInAppIdKey;//領英appid
NSString * const ACLinkedInPermissionsKey; //設定許可權key
//騰訊微博
NSString *const ACTencentWeiboAppIdKey; //設定appid

三、使用者資訊相關類解析

ACAccount類解析如下:

@interface ACAccount : NSObject
- (instancetype)initWithAccountType:(ACAccountType *)type;//構造方法
@property (readonly, weak, NS_NONATOMIC_IOSONLY) NSString      *identifier;//識別符號
@property (strong, NS_NONATOMIC_IOSONLY)   ACAccountType       *accountType;//賬戶型別
@property (copy, NS_NONATOMIC_IOSONLY)     NSString            *accountDescription;//賬戶描述
@property (copy, NS_NONATOMIC_IOSONLY)     NSString            *username;//使用者名稱
@property (readonly, NS_NONATOMIC_IOSONLY)  NSString           *userFullName;//完整名稱
@property (strong, NS_NONATOMIC_IOSONLY)   ACAccountCredential *credential;//授權憑證
@end

ACAccountCredential類解析如下:

@interface ACAccountCredential : NSObject
//構造方法
- (instancetype)initWithOAuthToken:(NSString *)token tokenSecret:(NSString *)secret;
- (instancetype)initWithOAuth2Token:(NSString *)token 
                       refreshToken:(NSString *)refreshToken
                         expiryDate:(NSDate *)expiryDate;
//token
@property (copy, nonatomic) NSString *oauthToken;
@end

四、ACAccountStore類解析

@interface ACAccountStore : NSObject
//所有賬戶列表
@property (readonly, weak, NS_NONATOMIC_IOSONLY) NSArray *accounts;
//根據id獲取賬戶
- (ACAccount *)accountWithIdentifier:(NSString *)identifier;
//根據id獲取賬戶型別物件
- (ACAccountType *)accountTypeWithAccountTypeIdentifier:(NSString *)typeIdentifier;
//獲取指定型別的所有賬戶
- (NSArray *)accountsWithAccountType:(ACAccountType *)accountType;
//進行賬戶儲存
- (void)saveAccount:(ACAccount *)account withCompletionHandler:(ACAccountStoreSaveCompletionHandler)completionHandler;
//進行賬戶使用許可權申請
- (void)requestAccessToAccountsWithType:(ACAccountType *)accountType
                  withCompletionHandler:(ACAccountStoreRequestAccessCompletionHandler)handler NS_DEPRECATED(NA, NA, 5_0, 6_0);
- (void)requestAccessToAccountsWithType:(ACAccountType *)accountType
                                options:(NSDictionary *)options
                             completion:(ACAccountStoreRequestAccessCompletionHandler)completion;
//如果賬戶許可權已經過期 呼叫此方法進行重新整理
- (void)renewCredentialsForAccount:(ACAccount *)account completion:(ACAccountStoreCredentialRenewalHandler)completionHandler;
//刪除賬戶
- (void)removeAccount:(ACAccount *)account withCompletionHandler:(ACAccountStoreRemoveCompletionHandler)completionHandler;
@end

千里之遙始於足下,冰凍三尺非一日之寒

——共勉