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; @synthesize password1;

- (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

このように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 に答える
0

最も簡単な解決策は、キーチェーンを使用することです。

もう 1 つの簡単な方法は、ログイン資格情報をロケール ファイル (txt、xml、さらには sqldb) に保存することです。

于 2012-10-04T12:50:01.740 に答える