为 iOS 开发应用程序时,我需要知道如何在用户进行身份验证时创建实例化和可用的对象。
我正在使用 OAuth2 方法正确实现 gtm-oauth2 框架。用户条目会看到显示在 Web 视图中的登录表单并正确进行身份验证。在那一刻,如文档中所述,我是这样的:
if (error != nil){
// Do whatever to control the error
}
else
{
// Authentication succeeded
// Assign the access token to the instance property for later use
self.accessToken = myAuth.accessToken;
[myAuth setShouldAuthorizeAllRequests:YES];
[self setAuth:myAuth];
// Display the access token to the user
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Authorization Succeeded"
message:[NSString stringWithFormat:@"Access Token: %@", myAuth.accessToken]
delegate:self
cancelButtonTitle:@"Dismiss"
otherButtonTitles:nil];
[alertView show];
}
稍后,在同一个控制器中,一旦用户通过身份验证,我就会使用这样的 self.auth 对象来访问我的 API:
[request setURL:getCartsURL];
[request setValue:self.accessToken forHTTPHeaderField:@"Authorization"];
[self.auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
// Synchronous fetches like this are a really bad idea in Cocoa applications
//
// For a very easy async alternative, we could use GTMHTTPFetcher
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [SBJsonParser new];
// Parse the JSON into an Object
id parsed = [jsonParser objectWithString:output];
NSArray *arrayResponse = [[NSArray alloc] initWithArray:parsed];
} else {
// fetch failed
output = [error description];
}
}
}];
到目前为止,我一直在使用self.auth
对象的本地实例,如果我想从整个应用程序的任何点全局访问该对象,这还不够。对于初始化视图控制器可以,但对于整个应用程序则不行。
我想我可以随时访问第一个视图控制器来获取对象。但我想我们有更好的方法让它全局实例化并从应用程序的任何点访问。
你能帮我解决这个问题吗?
非常感谢。