1

我是 iOS 开发的新手。我正在开发照片共享应用程序。在此,首先我需要为登录页面使用 Web 服务。Web 服务使用 PHP 并以 JSON 格式返回响应。我想在整个应用程序中保存登录会话。当用户启动应用程序时,它总是检查用户是否登录。如果我不及早这样做,请尽快给我合适的解决方案,因为我的工作有最后期限。这是我的代码。

**<HomeKiddoAppDelegate.h file>**

#import <UIKit/UIKit.h>

    @class HomeKiddoViewController;


    @interface HomeKiddoAppDelegate : UIResponder <UIApplicationDelegate>

    @property (strong, nonatomic) UIWindow *window;

    @property (strong, nonatomic) HomeKiddoViewController *viewController;

@end



**<HomeKiddoAppDelegate.m  file>**


#import "HomeKiddoAppDelegate.h"

#import "HomeKiddoViewController.h"


@implementation HomeKiddoAppDelegate



     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:    (NSDictionary *)launchOptions
        {
            self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            // Override point for customization after application launch.
           self.viewController = [[HomeKiddoViewController alloc]     initWithNibName:@"HomeKiddoViewController" bundle:nil];
           self.window.rootViewController = self.viewController;
           [self.window makeKeyAndVisible];

        //Register defaults
            NSMutableDictionary *defaultsDictionary = [[NSMutableDictionary alloc] init];
          [[NSUserDefaults standardUserDefaults] registerDefaults: defaultsDictionary];

        return YES;
    }

    - (void)applicationWillResignActive:(UIApplication *)application
    {

    }

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {

    }

    - (void)applicationWillEnterForeground:(UIApplication *)application
    {

    }

    - (void)applicationDidBecomeActive:(UIApplication *)application
    {

    }

    - (void)applicationWillTerminate:(UIApplication *)application
    {

    }

@end

    > #import <UIKit/UIKit.h>
    > #import "SignInViewController.h"
    > 
    > @interface HomeKiddoViewController : UIViewController{
    >     SignInViewController *signInViewController;
    >     }
    > 
    > -(IBAction)signInClicked:(id)sender;
    > 
    > @end

**<HomekiddoViewController.m>**
> #import "HomeKiddoViewController.h"
> 
> @interface HomeKiddoViewController ()
> 
> @end
> 
> @implementation HomeKiddoViewController
> 
>      - (void)viewDidLoad
>     {
>         [super viewDidLoad];
>     }
> 
>     - (void)viewDidUnload    {
>        [super viewDidUnload];    }
> 
>     - (BOOL)shouldAutorotateToInterfaceOrientation:      (UIInterfaceOrientation)interfaceOrientation    {
>         return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);    }
> 
>    -(IBAction)signInClicked:(id)sender{
>         if(signInViewController==nil){
>             signInViewController=[[SignInViewController alloc]initWithNibName:@"SignInViewController" bundle:nil];
>         }
>        [self.view addSubview:signInViewController.view];
>     } @end
> 
> 

    **<SignInFormViewController.h>**
    > #import <UIKit/UIKit.h>
    > #import "SBJson.h"

    > 
    > @interface SignInFormViewController : UIViewController
    > <NSURLConnectionDelegate>

        {
        >     IBOutlet UITextField *email1;
        >     IBOutlet UITextField *password1;
        >     NSURLConnection *conn;
        >     NSMutableData *webData;
        >     IBOutlet UITextView *textView;
        >    }

     @

        property (nonatomic, retain) IBOutlet UITextField *email1; @property
        > (nonatomic, retain) IBOutlet UITextField *password1;

    > 
    > 

        -(IBAction)btnSignInClicked:(id)sender;
        > -(IBAction)backClicked:(id)sender;

    > 
    > @end
    > 

导入“SignInFormViewController.h”

@interface SignInFormViewController ()

@结尾

@implementation SignInFormViewController @synthesize email1; @合成密码1;

- (void)viewDidLoad

    {
        [super viewDidLoad];
    }

- (void)viewDidUnload

{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(IBAction)btnSignInClicked:(id)sender{
        NSString *queryUrl=[NSString stringWithFormat:@"Url of the web service with   parameters",email1.text,password1.text];
        NSURL *url=[NSURL URLWithString:queryUrl];
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
        conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
        if(conn)
        {
            webData=[NSMutableData data];
            NSLog(@"in Connection if statement");
        }
}

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response{

        [webData setLength: 0];
        NSLog(@" inside didReceiveZResponse");
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data {
    [webData appendData:data];
    NSLog(@"inside did receive data");

}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error {

    NSLog(@"in fail with error");

}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection{

    [email1 resignFirstResponder];
    [password1 resignFirstResponder];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:email1.text forKey:@"email"];
    [defaults setObject:password1.text forKey:@"password"];
    [defaults synchronize];   
}

-(IBAction)backClicked:(id)sender{
    [self.view removeFromSuperview];
}

@结尾

4

3 回答 3

4

我会给你一个全面的答案。

不要使用 NSUserDefaults 并且不要存储密码,这是一个糟糕的解决方案

让我们创建一个结构化的用户类

当用户登录时,您需要确保您可以访问整个应用程序中的用户数据,以便您可以在需要时在任何屏幕上获取数据。

为了实现这一点,我们需要建立一个很好的结构来适当地组织它。请记住,当前用户和其他用户都是“用户”,因此我们将使用相同的类。

创建一个类并将其命名为“EDUser”(如果需要,您可以选择其他名称)。
此类将包含用户信息(当前用户或其他用户)。
不仅如此,这个类将有能力让用户登录。

这是该类可能的样子的图片:

class EDUser {
    var firstName: String
    var lastName: String?
    var birthDate: NSDate?

    init(firstName: String, lastName: String?, birthDate: NSDate?) {
        self.firstName = firstName
        self.lastName = lastName
        self.birthDate = birthDate
    }
}

// MARK: - Accessor

extension EDUser {
    class var currentUser: EDUser? {
        get {
            return loadCurrentUserFromDisk()
        }
        set {
            saveCurrentUserToDiskWithUser(newValue)
        }
    }
}

// MARK: - Log in and out

extension EDUser {
    class func loginWithUsername(username: String,
                           andPassword password: String,
                           callback: (EDUser?, NSError) -> Void) {
        // Access the web API
        var parameters = [
            "username": username,
            "password": password
        ]
        YourNetworkingLibrary.request(.POST,
                          "https://api.yourwebsite.com/login",
                          parameters: parameters).responseJSON { 
            response in

            if response.statusCode == .Success {
                let user = EDUser(firstName: response["firstName"],
                       lastName: response["lastName"],
                       birthDate: NSDate.dateFromString(response["birthDate"]))
                currentUser = user
                callback(currentUser, nil)
            } else {
                callback(nil, yourError)
            }
        }
    }

    class func logout() {
        deleteCurrentUserFromDisk()
    }
}

// MARK: - Data

extension EDUser {
    class private func saveCurrentUserToDiskWithUser(user: EDUser) {
        // In this process, you encode the user to file and store it
    }

    class private func loadCurrentUserFromDisk() -> EDUser? {
        // In this process, you get the file and decode that to EDUser object
        // This function will return nil if the file is not exist
    }

    class private func deleteCurrentUserFromDisk() {
        // This will delete the current user file from disk
    }
}

// MARK: - Helper

extension NSDate {
    class func dateFromString(string: String) -> NSDate {
        // convert string into NSDate
    }
}

用例

现在一切就绪,我们可以像这样使用它

非阻塞登录进程

EDUser.loginWithUsername(username: "edward@domain.com",
                         password: "1234") {
    user, error in

    if error == nil {
        // Login succeeded
    } else {
        // Login failed
    }
}

注销

EDUser.logout()

检查用户是否登录

if EDUser.currentUser != nil {
    // The user is logged in
} else {
    // No user logged in
    // Show the login screen here
}

在任何屏幕上获取当前用户数据

if let currentUser = EDUser.currentUser {
    // do something with current user data
}

将其他用户存储为对象

let user = EDUser(firstName: "Edward",
                  lastName: "Anthony",
                  birthDate: NSDate())
于 2016-06-16T22:29:47.260 回答
0

最简单的解决方案是使用钥匙串。

另一种简单的方法是将登录凭据保存在语言环境文件(txt、xml 甚至 sqldb)中。

于 2012-10-04T12:50:01.740 回答
0

您可以像这样将登录数据保存在 NSUserDefaults 中。

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:cookieString forKey:@"Cookie"];
[userDefaults setObject:pwString forKey:@"Password"];
[userDefaults synchronize];

然后,您可以从应用程序中您喜欢的任何位置加载用户默认值

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *myString = [defaults objectForKey:@"Cookie"];
于 2012-10-04T13:14:21.887 回答