分享

在Objective C中保持会话

 软件团队头目 2013-01-14

So i got the following problem:

I got a login viewcontroller and a form viewcontroller. On the login viewcontroller, i am sending a POST request to a PHP script which validates if the user has access. The script just returns an 1 or 0. So i can then choose to dismiss or maintain the viewcontroller. When the credentials are passed right, the user will see the form controller. This controller got a button to fetch a form.

The button to fetch the form, makes a POST request to another PHP script, which will return an XML document with the values of the user. I need a way to remember the username and password the user has passed through. So i can use them in another (view) controller.

Does anybody know a way to achieve this?

share|edit|flag

1 upvote
 flag
What’s your target platform: Mac OS X or iOS? Use the cocoa tag for Mac OS X; use the cocoa-touch tag for iOS. – Bavarious Aug 12 '11 at 10:16
  upvote
 flag
Add the user name and password into a plist. – Robin Aug 12 '11 at 10:22

3 Answers

up vote 5 down vote accepted

If you're using NSURLConnection, and the session is cookie based, this would automatically be done. So all you'd need to write would be similar to this

NSMutableURLRequest *request = nil;
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///login.php"]];

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@", @"<username>", @"<password>"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_urlConnection start];

And you would have to implement the NSURLConnectionDelegate methods as well

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //Oops! handle failure here
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (_statusCode >= 200 && _statusCode < 400) {
            //Things look ok
        NSString *responseString = [[[NSString alloc] initWithData:_responseData] autorelease];
        //Send this to an xml lib and parse
        }

    [_responseData release];
    _responseData = nil;
    [connection autorelease];
}

If you have some other information thats in the headers and which you need to send back with consequent requests, you can read it from the response like this

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields]; //This would give you all the header fields;
    }
}

And set the header fields for the next request like this

    [request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];

To save information, be it username and/or password or session information you can use NSUserDefaults

    //To save
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

if (standardUserDefaults) {
    [standardUserDefaults setObject:@"<username>" forKey:@"username"];
    [standardUserDefaults setObject:@"<pass>" forKey:@"password"];
    [standardUserDefaults synchronize];
}

//To retrieve
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;

if (standardUserDefaults) 
    val = [standardUserDefaults objectForKey:@"username"];

Lastly, it would be advisable to build a model to map the xml API with [Eg: a User class with username and password properties].

Google for Apple's docs on MVC.

Hope this helps!

share|edit|flag
  upvote
 flag
I am using the ASIHTTPRequest class. So NSURLConnection is not gonna work for me. – Jack Aug 12 '11 at 11:27
  upvote
 flag
Even better! Just make sure that useCookiePersistance is turned on. Also you can manually manage the cookies as well. Check this /ASIHTTPRequest/How-to-use#persistent_cookies – Abhinit Aug 12 '11 at 12:14

Yeah ASI HTTP Request is derived basically from NSURL class only..u need not worry about HTTP call back.just store those values in plist of use sqlite for complex and huge data storage purpose

share|edit|flag

Create a "model" object for your program (have a look at the model-view-controller pattern, which is ubiquitous in cocoa), then in your login controller, store username and password in the model; then, from wherever you need access those data, you read them from the model.

share|edit|flag

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多