带有来自 WebService 的会话 ID 的 IOS 登录 JSON 解析器
Posted
技术标签:
【中文标题】带有来自 WebService 的会话 ID 的 IOS 登录 JSON 解析器【英文标题】:IOS Login JSON parser with session Id from WebService 【发布时间】:2014-11-14 09:21:28 【问题描述】:您好,我是 ios 开发新手。我正在开发一个从 web 服务中提取数据的应用程序。它具有登录和注销会话以及我打算使用 RestKit 实现的大量 JSON API 调用。
现在的问题是我的登录工作正常并获得成功代码 200 但无法转到下一个视图控制器场景,因为。我不知道如何获取 sessionId。
这是我的代码和 JSON;
"details":
"username": "MY USER NAME",
"password": "MY MD5 CONVERTED PASS"
Expected Returned JSON syntax (Success)
"response":
"code": 200,
"resp_code": "USER_SESSION_LOGGED_IN", "sid": "as4ads68ds468486essf879g8de9sdg", "session_info":
"details":
"firstname" : "MY NAME",
"email_address" : "MY EMAIL", "company_id" : 1,
"user_id" : 1,
"surname" : "MY SURNAME",
"cell_number" : "MY NUMBER",
"username" : "MY USERNAME"
//
// ViewController.m
//
// Created by Cockpit Alien on 2014/10/27.
// Copyright (c) 2014 CockpitAlien. All rights reserved.
//
#import "ViewController.h"
#import <CommonCrypto/CommonDigest.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
/*+ (NSString*)md5HexDigest:(NSString*)input
const char* str = [input UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++)
[ret appendFormat:@"%02x",result[i]];
return ret;
*/
- (NSString *) md5:(NSString *) input
const char *cStr = [input UTF8String];
unsigned char digest[16];
CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
- (IBAction)signinClicked:(id)sender
NSInteger success = 0;
NSString *username = self.txtUsername.text;
NSString *password = self.txtPassword.text;
NSString *md5Password = [self md5:password];
@try
if([username isEqualToString:@""] || [password isEqualToString:@""] )
[self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];
else
NSString *post = [[NSString alloc] initWithFormat:@"username=%@&password=%@",username,md5Password];
NSLog(@"PostData: %@",post);
// Create the request
NSURL *url=[NSURL URLWithString:@"MY JSON HTTP/S URL HERE"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSLog(@"Request Mutable, %@", request);
[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;
// Create url connetion and fire requests
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];
NSLog(@"Loging failed");
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];
@end
//
// ViewController.h
//
// Created by CockPit on 2014/10/27.
// Copyright (c) 2014 CockpitAliens. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *txtUsername;
@property (weak, nonatomic) IBOutlet UITextField *txtPassword;
- (IBAction)signinClicked:(id)sender;
@end
这是我的故事板。我希望能够登录并转到下一个视图控制器。因为我还必须注销解析此 JSON 的 sessionId。
【问题讨论】:
NSLog(@"Response ==> %@", responseData);
告诉你什么
我将发布我现在得到的响应数据
发布数据:username=cockpit&password=vsgsvah24bsbsbs5tbsb
那是你的post数据,我们需要查看响应数据
检查segue Identifier是否正确,应该和xib一样
【参考方案1】:
在你的signinClicked
方法中,
- (IBAction)signinClicked:(id)sender
....
....
if ([response statusCode] >= 200 && [response statusCode] < 300)
....
....
if(success == 1)
NSLog(@"Login SUCCESS");
....
....
....
....
所以你除了打印 NSLog 之外什么也没做。您正在检查 statusCode 是否成功以及检查 success 变量值。在这种情况下,您应该需要可执行代码或方法调用,这将推动应用程序进一步执行。
【讨论】:
是的,如果(成功 == 1)我相信你是对的,我相信应该有一个代码来操作在这种情况下下一步该做什么。请帮忙 if(success == 1) NSLog(@"登录成功"); [self performSegueWithIdentifier:@“登录成功”发件人:self]; 其他 如果我添加此代码仍然无法让视图控制器进入登录成功屏幕 那么你的故事板segue连接一定有问题。尝试删除您当前的连接并添加具有不同标识符名称的新连接。 这就是响应。除非我不明白你的意思。以上是关于带有来自 WebService 的会话 ID 的 IOS 登录 JSON 解析器的主要内容,如果未能解决你的问题,请参考以下文章
为啥不使用长寿命会话 ID 来代替带有令牌的持久 cookie?
无法从带有 Socket.IO 的 cookie 中获取 Express 会话 ID