我在视图控制器中有登录按钮的操作,但我必须在appdelegate.m
中使用某些条件,如果用户已登录,则viewcontroller
登录操作方法将触发,如果未登录,则仅登录页面会打开吗?
请帮帮我
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([[NSUserDefaults standardUserDefaults]boolForKey:@"IsFirstTime"])
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
HomePageVC *lvc = [storyboard instantiateViewControllerWithIdentifier:@"HomePageVC"];
[(UINavigationController *)self.window.rootViewController pushViewController:lvc animated:NO];
}
else
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"IsFirstTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
return YES;
}
在viewcontroller.m中
- (IBAction)Login:(id)sender
{
[self.indicator startAnimating];//The ActivityIndicator Starts Animating Here
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl@"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"*/*" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSString *mapData = [NSString stringWithFormat:@"userName=gautam.kar@eyeforweb.com&userPassword=1234567&api_key=ZWZ3QDEyMw==&api_password=456789"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"jsondic= %@",jsonDic);
NSDictionary *userDataDic = [jsonDic objectForKey:@"record"];
[DataModel setEmailAdd:[userDataDic objectForKey:@"emailAdd"]];
[DataModel setName:[userDataDic objectForKey:@"Name"]];
[DataModel setCity:[userDataDic objectForKey:@"city"]];
[DataModel setCountry:[userDataDic objectForKey:@"country"]];
[DataModel setRegistrationID:[userDataDic objectForKey:@"registrationID"]];
[DataModel setPhoneNo:[userDataDic objectForKey:@"phoneAdd"]];
[DataModel setState:[userDataDic objectForKey:@"state"]];
[DataModel settimeZone:[userDataDic objectForKey:@"timezone"]];
[DataModel setDisclaimer:[userDataDic objectForKey:@"disclaimer"]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];//The ActivityIndicator Stops Animating when Response Arrives
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"text= %@",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self checkUserSuccessfulLogin:json];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];
});
NSLog(@"Error : %@",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:@"login"])
{
if ([[dictionary objectForKey:@"login"] boolValue])
{
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:@"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:@"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"user_id"] forKey:@"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:@"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
HomePageVC *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"HomePageVC"];
[self.navigationController pushViewController:vc animated:YES];
}
else
{
NSLog(@"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Wrong Username Or Password" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:@"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(@"Saved");
}
else
{
NSLog(@"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:@"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
答案 0 :(得分:1)
你需要的是不要在AppDelegate.m中检查你的控制器,即使这就是你所要求的。
您真正的问题是“如何从两个不同的地方访问数据?”。
现在,你告诉AppDelegate他“知道”你的视图控制器。它不应该。
你需要的是一个(实际上还有很多,但你会随着时间的推移了解到)新的类,它处理登录调用和状态,以及所有与登录相关的内容。
将该课程称为...... LoginManager
。
在该课程中,您可以使用一些方法,例如Login()或Logout(),或任何您想要的方法。
现在您拥有外部数据源,您的登录管理员知道他必须知道的有关登录的所有信息。您甚至应该添加一些属性,例如布尔值IsLoggedIn
或您可能需要的任何属性。
这些数据来源是AppDelegate需要知道的。不是控制器。有了这种架构,需要登录信息的每个人都可以从该类访问它(可能/应该是singleton
类,在互联网上查找,非常简单。
在您的viewcontroller中,您只需执行Loginmanager.login
,在appdelegate中,您可以检查.isloggedin
。
这对你有很大的帮助,因为你不必在appdelegate中实例化视图控制器,这真的是很多工作。你正在分割工作和类之间的任务,这是一个优秀的程序员所做的。请记住,你的班级应该只有一份工作,而不是更多,而不是更少。你的VC处理用户界面,而不是webservic调用,而不是登录,没有。如果是,则表示您需要创建另一个类:)
一旦你实现了所有这些(必要时多次阅读我的答案,以确保你理解),你可以在你的应用程序的其他地方访问这类数据没有问题。
请注意,您不应该滥用单例类或静态类(尤其是静态类),但同样,您可能会犯很多错误并从中学习,就像我们在开始时所做的那样。
答案 1 :(得分:0)
创建您的ViewController对象,如下所示
viewcontroller *objYourVC=[[viewcontroller alloc]init];
现在从Appdelegate
调用方法,如下所示:
[objYourVC functionToBeCalled:nil];
OR
[objYourVC functionToBeCalled:self];
实施例,
if(AlreadyLogin){
//call viewcontroller method
viewcontroller *objYourVC=[[viewcontroller alloc]init];
[objYourVC functionToBeCalled:nil];
}