2014-10-16 3 views
0

Я немного новичок в разработке iOS, поэтому я пытаюсь выяснить размещение строки JSON на веб-сервере и получение некоторой информации. На первой странице я прошу пользователя дать мне свое имя и фамилию. Затем я генерирую идентификатор для них и передаю их на вторую страницу. Когда загружается вторая страница, я хочу отправить строку JSON на сервер, чтобы указать имя пользователя, фамилию и многое другое. Запрос будет походить следующим образом:POST JSON to Server from CoreData Information

{ 
"user":{ 
    "first_name":"Joe", 
    "last_name":"User", 
    "device_descriptor":"iPhone", 
    "idfa":"12345678", 
    "btmacid":"01:23:45:67:89:ab" 
    } 
} 

создать ответ успешный вернется следующим образом:

{ 
    "id": "8", 
    "first_name: "Joe", 
    "last_name": "User", 
    "device_descriptor": "iPhone", 
    "created_at": "2014-10-07T05:25:36.119Z", 
    "updated_at": "2014-10-07T05:25:36.119Z", 
    "idfa": "12345678", 
    "btmacid": "01:23:45:67:89:ab" 
} 

кода я до сих пор выглядит следующим образом:

#import "WelcomeViewController.h" 
#import "CoreDataStack.h" 
#import "UserInformation.h" 
#import <CoreData/CoreData.h> 
#import <RestKit/RestKit.h> 

@interface WelcomeViewController() 

@property (nonatomic,strong) NSFetchedResultsController *fetchResultsController; 

@property (strong, nonatomic) IBOutlet UILabel *welcomeTextLabel; 

@end 

@implementation WelcomeViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 

    [self.fetchResultsController performFetch:nil]; 

    UserInformation *entry = [[self.fetchResultsController fetchedObjects] objectAtIndex:0]; 

    _welcomeTextLabel.text = [NSString stringWithFormat: @"Welcome " @"%@!", entry.firstName]; 

    [self postUserInformation]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (NSFetchRequest *)entryFetchRequest{ 
    NSFetchRequest *fetchReqeust = [NSFetchRequest fetchRequestWithEntityName:@"UserInformation"]; 

    fetchReqeust.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]]; 

    return fetchReqeust; 
} 

- (NSFetchedResultsController *)fetchResultsController { 
    if (_fetchResultsController != nil) { 
     return _fetchResultsController; 
    } 

    CoreDataStack *coreDataStack = [CoreDataStack defaultStack]; 
    NSFetchRequest *fetchRequest = [self entryFetchRequest]; 

    _fetchResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:coreDataStack.managedObjectContext sectionNameKeyPath:nil cacheName:nil]; 

    return _fetchResultsController; 
} 

- (void) postUserInformation { 
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES; 

    [self.fetchResultsController performFetch:nil]; 

    UserInformation *entry = [[self.fetchResultsController fetchedObjects] objectAtIndex:0]; 


    RKObjectManager *manager = [RKObjectManager sharedManager]; 
    RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[UserInformation class]]; 
    NSDictionary *userInformation = @{ 
             @"id"     : @"userID", 
             @"first_name"   : @"firstName", 
             @"last_name"   : @"lastName", 
             @"device_descriptor" : @"deviceHardwareID", 
             @"created_at"   : @"created_at", 
             @"updated_at"   : @"updated_at", 
             @"idfa"    : @"deviceAdvertisementID", 
             @"btmacid"   : @"btmac_Id" 
             }; 
    [responseMapping addAttributeMappingsFromDictionary:userInformation]; 

    manager.requestSerializationMIMEType = RKMIMETypeJSON; 

    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); 
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodAny pathPattern:@"/users" keyPath:nil statusCodes:statusCodes]; 

    RKObjectMapping *requestMapping = [RKObjectMapping requestMapping]; 
    [requestMapping addAttributeMappingsFromDictionary:userInformation]; 

    RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[userInformation class] rootKeyPath:nil method:RKRequestMethodAny]; 

    [manager addResponseDescriptor:responseDescriptor]; 
    [manager addRequestDescriptor:requestDescriptor]; 

// NSDictionary *params = @{ 
//        @"id"     : entry.userID, 
//        @"first_name"   : entry.firstName, 
//        @"last_name"   : entry.lastName, 
//        @"device_descriptor" : entry.deviceHardwareID, 
//        @"created_at"   : entry.createdAt, 
//        @"updated_at"   : entry.updatedAt, 
//        @"idfa"    : entry.deviceAdvertisementID, 
//        @"btmacid"   : entry.btmacID 
//        }; 

    [manager postObject:userInformation path:@"http://serverendpoint.com/users" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
     NSLog(@"Success"); 
    } failure:^(RKObjectRequestOperation *operation, NSError *error) { 
     NSLog(@"Failure: %@", error); 
    }]; 

} 


/* 
#pragma mark - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
// Get the new view controller using [segue destinationViewController]. 
// Pass the selected object to the new view controller. 
} 
*/ 

@end 

Любая помощь вы все могли бы предоставить.

ответ

0

Вы не должны создавать отображение запроса с

[requestMapping addAttributeMappingsFromDictionary:userInformation]; 

Поскольку входы и выходы неправильный путь вокруг. Вместо этого используйте inverseMapping из вашего сопоставления ответов.