你說得對。將這個功能構建到視圖控制器中是不必要的,而且封裝很差
在MVC範例中,模型通常具有數據上下文。數據上下文管理與後端存儲(在iOS中,這往往是一個Web服務或本地文件)的通信來填充和存檔模型對象。對於經過身份驗證的數據上下文,您擁有用戶名,密碼和身份驗證狀態的屬性。
@interface DataContext : NSObject
//Authentication
@property (nonatomic, strong) NSString * username;
@property (nonatomic, strong) NSString * password;
@property (nonatomic, assign) NSInteger authenticationState;
-(void)login;
//Data object methods from authenticated data source (web service, etc)
-(NSArray *)foos;
-(NSArray *)bars;
@end
認證狀態可以是一個簡單的布爾或整數,如果你想跟蹤許多國家(認證,未經認證,試圖與存儲的證書認證未認證後)。 您現在可以觀察到authenticationState
屬性,以允許您的控制器層對身份驗證狀態的更改採取操作。
請求時從Web服務數據,更改時,服務器拒絕請求的認證狀態由於憑據無效
-(NSArray *)foos
{
NSArray * foos = nil;
//Here you would make a web service request to populate the foos array from your web service.
//Here you would inspect the status code returned to capture authentication errors
//I make my web services return status 403 unauthorized when credentials are invalid
int statusCode = 403;
if (statusCode == 403)
{
self.authenticationState = 0;//Unauthorized
}
return foos;
}
該控制器是應用程序委託。它存儲我們的DataContext的實例。它會觀察對該authenticated
屬性的更改,並在適當時顯示視圖或重新嘗試身份驗證。
- (void)observeAuthenticatedState:(NSNotification *)notification
{
DataContext * context = [notification object];
if (context.authenticatedState == 0)//You should have constants for state values if using NSIntegers. Assume 0 = unauthenticated.
{
[self.context login];
}
if (context.authenticatedState == -1)//You should have constants for state values if using NSIntegers. Assume -1 = unauthenticated after attempting authentication with stored credentials
{
UIViewController * loginController = nil;//Instantiate or use existing view controller to display username/password to user.
[[[self window] rootViewController] presentViewController:loginController
animated:YES
completion:nil];
}
if (context.authenticatedState == 1)//authenticated.
{
[[[self window] rootViewController] dismissViewControllerAnimated:YES
completion:nil];
}
}
在你的故事板,你基本上可以假裝認證不存在,因爲應用程序委託中插言的用戶界面認證每當數據上下文通信需要它的。
不能錯過一個有趣的答案:Q「誰應該負責以登錄形式顯示模態對話框?」答:「開發者」 - 不是? :) – 2013-10-31 17:48:02
@matheszabi呃哦,突然我想象每個iPhone都附加了數以萬計的「開發人員」 – sanmai