iOS - POST с RestKit: функции обратного вызова не вызываются - (используются данные отображения) - PullRequest
1 голос
/ 02 ноября 2011

Привет всем, это мой первый пост в переполнении стека,

Итак, во-первых, большое спасибо всем, кто поделился!

Мои проблемы:

  • Я не получаю обратный вызов при использовании RKObjectManager для объекта POST Serialized.
  • И я не знаю, правильно ли я использую данные картирования ...

Итак, я покажу вам результат моего бездействующего сервиса (отформатированный в JSON), мой код и мои журналы restkit

{"sessionId":"DA93D5ECD8E338AA27800794EEB9C20F","user":{"id":3,"ref":"2461498766","login":"clientTest","mail":"clientTest@Test.com","phone":"client127","subId":3,"creation":"29/03/2010 10:33:24","language":"en","firstConnection":"30/03/2010 16:42:07","lastConnection":"02/11/2011 09:36:43","connectionStep":"6"},"gateway":{"id":3,"serial":"testserial","status":"A","led":"START","ref":"DJJHGGGG00009","type":"FULL","ip":"192.168.44.168","connection":"","initDate":1290694795533,"activationDate":1290694795533,"manufacDate":1269851384000,"imei":"354482020013035","model":"TYLOP","firmware":"1.3.1","version":"","macWifi":"...","macEthernet":"...","updateDate":1310053274000,"muteMode":"","timezone":""}}

Как видите, у нас есть глобальный объект с внутренним объектом: пользователь, объекты шлюза.

VOAuth.h, мой глобальный объект, используемый для отображения данных:

#import "VOUser.h"
#import "VOGateway.h"

@interface VOAuth : NSObject
@property (nonatomic, retain) NSString * sessionId;
@property (nonatomic, retain) VOUser * user;
@property (nonatomic, retain) VOGateway * gateway;
@end

VOGateway.h,

#import <Foundation/Foundation.h>

@interface VOGateway : NSObject

@property (nonatomic, retain) NSString * identifier;
@property (nonatomic, retain) NSString * serial;
@property (nonatomic, retain) NSString * status;
@property (nonatomic, retain) NSString * led;
@property (nonatomic, retain) NSString * ref;
@property (nonatomic, retain) NSString * type;
@property (nonatomic, retain) NSString * ip;
@property (nonatomic, retain) NSString * connection;
@property (nonatomic, retain) NSString * initDate;
@property (nonatomic, retain) NSString * activationDate;
@property (nonatomic, retain) NSString * manufacDate;
@property (nonatomic, retain) NSString * imei;
@property (nonatomic, retain) NSString * model;
@property (nonatomic, retain) NSString * firmware;
@property (nonatomic, retain) NSString * version;
@property (nonatomic, retain) NSString * macWifi;
@property (nonatomic, retain) NSString * macEthernet;
@property (nonatomic, retain) NSString * updateDate;
@property (nonatomic, retain) NSString * muteMode;
@property (nonatomic, retain) NSString * timezone;

@end

VOUser.h,

#import <Foundation/Foundation.h>

@interface VOUser : NSObject

@property (nonatomic, retain) NSString * identifier;
@property (nonatomic, retain) NSString * ref;
@property (nonatomic, retain) NSString * login;
@property (nonatomic, retain) NSString * mail;
@property (nonatomic, retain) NSString * phone;
@property (nonatomic, retain) NSString * subId;
@property (nonatomic, retain) NSString * creation;
@property (nonatomic, retain) NSString * language;
@property (nonatomic, retain) NSString * firstConnection;
@property (nonatomic, retain) NSString * lastConnection;
@property (nonatomic, retain) NSString * connectionStep;

@end

SOAuth.h (мой сериализованный объект, используемый в качестве параметров для моего вызова),

#import <Foundation/Foundation.h>

@interface SOAuth : NSObject
@property (nonatomic, retain) NSString* login;
@property (nonatomic, retain) NSString* password;
@end

MAModule.h (Мой менеджер, я звоню здесь, на мой отдых),

#import <Foundation/Foundation.h>
#import <RestKit/RestKit.h>
#import "VOUser.h"
#import "VOGateway.h"
#import "VOAuth.h"
#import "SOAuth.h"
@interface MAModule : NSObject <RKObjectLoaderDelegate>
-(void)sendLogIn;
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects;
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error;
@end

MAModule.m

#import "MAModule.h"

@implementation MAModule

-(void)sendLogIn
{

RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);

RKObjectManager* manager = [RKObjectManager    objectManagerWithBaseURL:@"http://mydomain.dev/ui/v1"];
[RKObjectManager sharedManager].serializationMIMEType = RKMIMETypeJSON;
[manager.router routeClass:[SOAuth class] toResourcePath:@"/auth" forMethod:RKRequestMethodPOST];

RKObjectMapping* authSerializationMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class] ];
[authSerializationMapping mapAttributes:@"login", @"password", nil];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:authSerializationMapping forClass:[SOAuth class] ];

RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[VOUser class]];
[userMapping mapKeyPath:@"id" toAttribute:@"identifier"];
[userMapping mapKeyPath:@"ref" toAttribute:@"ref"];
[userMapping mapKeyPath:@"login" toAttribute:@"login"];
[userMapping mapKeyPath:@"mail" toAttribute:@"mail"];
[userMapping mapKeyPath:@"phone" toAttribute:@"phone"];
[userMapping mapKeyPath:@"subId" toAttribute:@"subId"];
[userMapping mapKeyPath:@"creation" toAttribute:@"creation"];
[userMapping mapKeyPath:@"language" toAttribute:@"language"];
[userMapping mapKeyPath:@"firstConnection" toAttribute:@"firstConnection"];
[userMapping mapKeyPath:@"lastConnection" toAttribute:@"lastConnection"];
[userMapping mapKeyPath:@"connectionStep" toAttribute:@"connectionStep"];


RKObjectMapping *gatewayMapping = [RKObjectMapping mappingForClass:[VOGateway class]];
[gatewayMapping mapKeyPath:@"id" toAttribute:@"identifier"];
[gatewayMapping mapKeyPath:@"serial" toAttribute:@"serial"];
[gatewayMapping mapKeyPath:@"status" toAttribute:@"status"];
[gatewayMapping mapKeyPath:@"led" toAttribute:@"led"];
[gatewayMapping mapKeyPath:@"ref" toAttribute:@"ref"];
[gatewayMapping mapKeyPath:@"type" toAttribute:@"type"];
[gatewayMapping mapKeyPath:@"ip" toAttribute:@"ip"];
[gatewayMapping mapKeyPath:@"connection" toAttribute:@"connection"];
[gatewayMapping mapKeyPath:@"initDate" toAttribute:@"initDate"];
[gatewayMapping mapKeyPath:@"activationDate" toAttribute:@"activationDate"];
[gatewayMapping mapKeyPath:@"manufacDate" toAttribute:@"manufacDate"];
[gatewayMapping mapKeyPath:@"imei" toAttribute:@"imei"];
[gatewayMapping mapKeyPath:@"model" toAttribute:@"model"];
[gatewayMapping mapKeyPath:@"firmware" toAttribute:@"firmware"];
[gatewayMapping mapKeyPath:@"version" toAttribute:@"version"];
[gatewayMapping mapKeyPath:@"macWifi" toAttribute:@"macWifi"];
[gatewayMapping mapKeyPath:@"macEthernet" toAttribute:@"macEthernet"];
[gatewayMapping mapKeyPath:@"updateDate" toAttribute:@"updateDate"];
[gatewayMapping mapKeyPath:@"muteMode" toAttribute:@"muteMode"];
[gatewayMapping mapKeyPath:@"timezone" toAttribute:@"timezone"];

RKObjectMapping *authReturnMapping = [RKObjectMapping mappingForClass:[VOAuth class]];
[authReturnMapping mapKeyPath:@"sessionId" toAttribute:@"sessionId"];
[authReturnMapping mapKeyPath:@"user" toRelationship:@"user" withMapping:userMapping];
[authReturnMapping mapKeyPath:@"gateway" toRelationship:@"gateway" withMapping:gatewayMapping];
[[RKObjectManager sharedManager].mappingProvider setMapping:authReturnMapping forKeyPath:@""];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[authReturnMapping inverseMapping] forClass:[VOAuth class]]; 

NSLog(@"LOGIN SEND --------------------------------");    
SOAuth *logObj = [[SOAuth alloc]init];
logObj.login = @"clientTest";
logObj.password = @"216a2e1269b5daaa35fd911964e5a86ce11f267d";

RKObjectMapping* authhMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[VOAuth class] ];
[[RKObjectManager sharedManager] postObject:logObj mapResponseWith:authhMapping delegate:nil];
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
//RKLogInfo(@"Load collection of Articles: %@", objects);
NSLog(@"LOGIN OK --------------------------------");
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {
NSLog(@"LOGIN KO --------------------------------");
}

@end

Я бы хотел выделить несколько моментов:

  • [[RKObjectManager sharedManager] .mappingProvider setMapping: authReturnMapping forKeyPath: @ ""]: у меня есть пустой ключ для моего глобального сопоставления объектов, потому что у меня нет корневого ключа для него ...

  • [[RKObjectManager sharedManager] postObject: logObj mapResponseWith: делегат authhMapping: nil]; Мой делегат ноль, иначе мое приложение вылетает ...

ЛОГИ:

2011-11-02 11:04:50.824 RestKit Installation[3701:207] D restkit.network:RKClient.m:265 Reachability observer changed for client <RKClient: 0x6d06e10>, suspending queue (null) until reachability to host '0.0.0.0' can be determined
2011-11-02 11:04:50.827 RestKit Installation[3701:207] LOGIN SEND --------------------------------
2011-11-02 11:04:50.833 RestKit Installation[3701:207] D restkit.network:RKClient.m:378 Reachability to host '0.0.0.0' determined for client <RKClient: 0x6d06e10>, unsuspending queue <RKRequestQueue: 0x6d09c10 name=(null) suspended=YES requestCount=1 loadingCount=0/5>
2011-11-02 11:04:50.836 RestKit Installation[3701:207] D restkit.network:RKRequest.m:334 Sending asynchronous POST request to URL http://mydomain.dev/ui/v1/auth.
2011-11-02 11:04:50.836 RestKit Installation[3701:207] D restkit.network:RKObjectLoader.m:302 POST or PUT request for source object <SOAuth: 0x9001540>, serializing to MIME Type application/json for transport...
2011-11-02 11:04:50.838 RestKit Installation[3701:207] T restkit.network:RKRequest.m:282 Prepared POST URLRequest '<NSMutableURLRequest http://mydomain.dev/ui/v1/auth>'. HTTP Headers: {
Accept = "application/json";
"Content-Length" = 75;
"Content-Type" = "application/json";
}. HTTP Body:       {"login":"clientTest","password":"216a2e1269b5daaa35fd911964e5a86ce11f267d"}.
2011-11-02 11:04:51.432 RestKit Installation[3701:207] D restkit.network:RKResponse.m:196 NSHTTPURLResponse Status Code: 200
2011-11-02 11:04:51.433 RestKit Installation[3701:207] D restkit.network:RKResponse.m:197 Headers: {
Connection = close;
"Content-Length" = 763;
"Content-Type" = "application/json";
Date = "Wed, 02 Nov 2011 10:04:57 GMT";
}
2011-11-02 11:04:51.434 RestKit Installation[3701:207] T restkit.network:RKResponse.m:202 Read response body: {"sessionId":"DA93D5ECD8E338AA27800794EEB9C20F","user":{"id":3,"ref":"2461498766","login":"clientTest","mail":"clientTest@Test.com","phone":"client127","subId":3,"creation":"29/03/2010 10:33:24","language":"en","firstConnection":"30/03/2010 16:42:07","lastConnection":"02/11/2011 09:36:43","connectionStep":"6"},"gateway":{"id":3,"serial":"testserial","status":"A","led":"START","ref":"DJJHGGGG00009","type":"FULL","ip":"192.168.44.168","connection":"","initDate":1290694795533,"activationDate":1290694795533,"manufacDate":1269851384000,"imei":"354482020013035","model":"TYLOP","firmware":"1.3.1","version":"","macWifi":"...","macEthernet":"...","updateDate":1310053274000,"muteMode":"","timezone":""}}
2011-11-02 11:04:51.438 RestKit Installation[3701:6003] D restkit.network:RKObjectLoader.m:210 Found directly configured object mapping, creating temporary mapping provider for keyPath '%@'

Наконец,

Мои функции обратного вызова не вызываются:

  • (void) objectLoader: (RKObjectLoader *) objectLoader didLoadObjects: (NSArray *) объекты

  • (void) objectLoader: (RKObjectLoader *) objectLoader didFailWithError: (NSError *) ошибка

Надеясь, что кто-то может мне помочь,

TY.

1 Ответ

3 голосов
/ 03 ноября 2011

Ваши методы не вызываются, потому что вы устанавливаете nil в качестве вашего делегата.Согласно нашему последующему обсуждению, если self передается в качестве делегата, последующее падение вызвано слишком ранним освобождением MAModule.Используйте свойство или одноэлементный шаблон, чтобы сохранить объект MAModule как минимум до тех пор, пока ваши запросы не будут выполнены.

...