我一直在尝试获取在iOS应用中使用Session变量的帮助。我搜索的越多,我就越困惑。有些人说只是在NSUserDefaults中存储用户数据,其他人说在Auth Header中发送令牌,还有更多人说使用Session类方法并从每个类调用它
不幸的是现在我不知道我应该做什么。我有一个正常工作的登录脚本,并设置$ _SESSION变量,我只是不知道如何在应用程序中使用这些变量。
编辑清晰度
确定我真正需要的是一种将$ _SESSION变量回显到我的应用程序然后访问该信息的方法。我看过有关NSCookieStorage的信息,以及它自动存储cookie的事实是正确的吗?如果是的话,我该如何使用它?我是否必须回复结果以填充cookie或者当登录成功回来时是否自动发送了cookie?
登录脚本
//
// LoginViewController.m
// TESG-iConnect
//
// Created by TESG on 5/03/14.
// Copyright (c) 2014 TESG. All rights reserved.
//
#import "LoginViewController.h"
@interface LoginViewController ()
@end
@implementation LoginViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)signinClicked:(id)sender {
NSInteger success = 0;
@try {
if([[self.txtUsername text] isEqualToString:@""] || [[self.txtPassword text] isEqualToString:@""] ) {
[self alertStatus:@"Please enter TESG Portal Username and Password" :@"Sign in Failed!" :0];
} else {
NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.txtUsername text],[self.txtPassword text]];
NSLog(@"PostData: %@",post);
NSURL *url=[NSURL URLWithString:@"http://tesg.com.au/loginJson.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"Response ==> %@", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[@"success"] integerValue];
NSLog(@"Success: %ld",(long)success);
if(success == 1)
{
NSLog(@"Login SUCCESS");
} else {
NSString *error_msg = (NSString *) jsonData[@"error_message"];
[self alertStatus:error_msg :@"Sign in Failed!" :0];
}
} else {
//if (error) NSLog(@"Error: %@", error);
[self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
}
}
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
[self alertStatus:@"Sign in Failed." :@"Error!" :0];
}
if (success) {
[self performSegueWithIdentifier:@"login_success" sender:self];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
- (IBAction)backgroundTap:(id)sender {
[self.view endEditing:YES];
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
@end
php登录脚本
<?php
header('Content-type: application/json');
require_once('DbConnector.php');
$connector = new DbConnector();
$username=htmlspecialchars($_POST['username'],ENT_QUOTES);
$password=md5($_POST['password']);
$sql="SELECT id, username, password, access, name FROM users WHERE username='".$username."' AND enabled = '1'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$password)==0)
{
//now set the session from here if needed
$_SESSION['id']=$row['id'];
$_SESSION['username']=$row['username'];
$_SESSION['access']=$row['access'];
$_SESSION['name']=$row['name'];
//if($row['access']=='0')
//{
echo '{"success":1}';
} else {
echo '{"success":0,"error_message":"Username and/or password is invalid."}';
}
}else { echo '{"success":0,"error_message":"Username and/or password is invalid."}';}
?>
任何有关设置会话并使用它们来回发送数据的帮助都会很棒。