首先,我创建了一个名为 Login Request 的类。
登录请求.h
#import <Foundation/Foundation.h>
#import "RKObjectMapping.h"
@interface LoginRequest : NSObject
@property (nonatomic, strong) NSString* email;
@property (nonatomic, strong) NSString* password;
+(RKObjectMapping*)defineLoginRequestMapping;
@end
登录请求.m
#import "LoginRequest.h"
#import "RKObjectManager.h"
@implementation LoginRequest
@synthesize email;
@synthesize password;
+(RKObjectMapping*)defineLoginRequestMapping {
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[LoginRequest class]];
[mapping addAttributeMappingsFromDictionary:@{
@"email": @"email",
@"password": @"password",
}];
return mapping;
}
然后,我创建了一个 LoginManager 类来进行连接。
登录管理器.h
#import <Foundation/Foundation.h>
#import "RKObjectManager.h"
#import "LoginResponse.h"
#import "LoginRequest.h"
@interface LoginManager : NSObject
@property (nonatomic, strong) LoginRequest *dataObject;
@property (nonatomic, strong) RKObjectManager *objectManager;
@property (nonatomic, strong) AFHTTPClient * client;
-(void)LoginWithUserName:(NSString *)username password:(NSString*)password;
@end
登录管理器.m
#import "LoginManager.h"
#import "RKMIMETypeSerialization.h"
#import "RKLog.h"
#import "LoginRequest.h"
@implementation LoginManager
-(void)LoginWithUserName:(NSString *)email password:(NSString*)password {
LoginRequest *dataObject = [[LoginRequest alloc] init];
[dataObject setEmail:email];
[dataObject setPassword:password];
NSURL *baseURL = [NSURL URLWithString:@"http://www.myurl.com/tokens.json"];
AFHTTPClient * client = [AFHTTPClient clientWithBaseURL:baseURL];
[client setDefaultHeader:@"Accept" value:RKMIMETypeJSON];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
RKObjectMapping *requestMapping = [[LoginRequest defineLoginRequestMapping] inverseMapping];
[objectManager addRequestDescriptor: [RKRequestDescriptor
requestDescriptorWithMapping:requestMapping objectClass:[LoginRequest class] rootKeyPath:nil
]];
// what to print
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
RKLogConfigureByName("Restkit/Network", RKLogLevelDebug);
RKObjectMapping *responseMapping = [LoginResponse defineLoginResponseMapping];
[objectManager addResponseDescriptor:[RKResponseDescriptor
responseDescriptorWithMapping:responseMapping method:RKRequestMethodAny pathPattern:@"" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)
]];
[objectManager setRequestSerializationMIMEType: RKMIMETypeJSON];
[objectManager postObject:dataObject path:@""
parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(@"It Worked: %@", [mappingResult array]);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"It Failed: %@", error);
}];
}
最后,我在 MasterViewController.m 上调用 viewDidLoad 上的方法
[[LoginManager alloc] LoginWithUserName:@"mymail@test.com" password:@"mypassword"];