NSLocalizedDescription=(200-299) 中的预期状态代码,得到 422}

NSLocalizedDescription=Expected status code in (200-299), got 422}

我正在制作广告 post。我按照我认为正确的方式设置了所有内容,但是当我单击玻色子时 "cadastrar anuncio" 它 returns 这个错误 "got 422"。已经研究了错误但是根本无法修复。 这里有人经历过这个吗?

这是我的网络服务

#import "JVWebService.h"
#import <RestKit/RestKit.h>
#import "AppDelegate.h"
#import "JVUtils.h"
#import "Ads.h"

static NSString *kServerURL = @"http://localhost:3000";

@interface JVWebService ()
@property (strong, nonatomic) RKObjectManager *restKitObjectManager;
@property (strong, nonatomic) NSDictionary *adAttributes;
@property (strong, nonatomic) NSDictionary *postAdAttributes;
@property (strong, nonatomic) NSDictionary *userAttributes;
@property (strong, nonatomic) NSDictionary *postUserAttributes;
@end

#define kSuccessStatusCode RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)

@implementation JVWebService

+ (instancetype)sharedService {
    static JVWebService *sharedService = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        sharedService = [[self alloc] init];

        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        sharedService.restKitObjectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:kServerURL]];
        [sharedService.restKitObjectManager.HTTPClient setAuthorizationHeaderWithUsername:[[[AppDelegate sharedDelegate] currentUser] email]
                                                                                 password:[[[AppDelegate sharedDelegate] currentUser] password]];
    });
    return sharedService;
}

#pragma mark - User

- (void)getUserForEmail:(NSString *)email andPassword:(NSString *)password {
    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:User.class];
    [objectMapping addAttributeMappingsFromDictionary:self.userAttributes];

    RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
    [requestMapping addAttributeMappingsFromDictionary:self.postUserAttributes];

    NSString *path = @"/users/sign_in.json";

    RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping
                                                                                   objectClass:User.class
                                                                                   rootKeyPath:@"user"
                                                                                        method:RKRequestMethodAny];
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:objectMapping
                                                                                            method:RKRequestMethodAny
                                                                                       pathPattern:path
                                                                                           keyPath:@"user"
                                                                                       statusCodes:kSuccessStatusCode];
    [self.restKitObjectManager addRequestDescriptor:requestDescriptor];
    [self.restKitObjectManager addResponseDescriptor:responseDescriptor];

    User *user = [User new];
    user.email = email;
    user.password = password;

    [[NSUserDefaults standardUserDefaults] setObject:[[NSUUID UUID] UUIDString] forKey:@"authencity_token"];
    NSDictionary *params = @{@"authenticity_token" : [[NSUserDefaults standardUserDefaults] objectForKey:@"authencity_token"]};

    [self.restKitObjectManager.HTTPClient setAuthorizationHeaderWithUsername:email password:password];
    [self.restKitObjectManager postObject:user path:path parameters:params success:^(RKObjectRequestOperation *operation,
                                                                                     RKMappingResult *result){
        User *user = (User *)result.array.firstObject;
        user.password = password;
        [[AppDelegate sharedDelegate] login:user];

        [[AppDelegate sharedDelegate] setLoggedViaFacebook:NO];

        if ([self.serviceDelegate respondsToSelector:@selector(successfulRequestDidReturnObject:)])
            [self.serviceDelegate successfulRequestDidReturnObject:user];

    } failure:^(RKObjectRequestOperation *operation, NSError *error){
        RKLogError(@"Operation failed with error: %@", error);

        if ([self.serviceDelegate respondsToSelector:@selector(requestDidFailWithError:)])
            [self.serviceDelegate requestDidFailWithError:error];
    }];

    [self.restKitObjectManager removeResponseDescriptor:responseDescriptor];


    }





- (void)postAd:(Ads *)ad {
    NSString *path = @"/ads.json";

    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:Ads.class];
    [objectMapping addAttributeMappingsFromDictionary:self.adAttributes];

    RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
    [requestMapping addAttributeMappingsFromDictionary:self.postAdAttributes];

    RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping
                                                                                   objectClass:Ads.class
                                                                                   rootKeyPath:@"ad"
                                                                                        method:RKRequestMethodAny];
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:objectMapping
                                                                                            method:RKRequestMethodAny
                                                                                       pathPattern:path
                                                                                           keyPath:@"ad"
                                                                                       statusCodes:kSuccessStatusCode];

    [self.restKitObjectManager addRequestDescriptor:requestDescriptor];
    [self.restKitObjectManager addResponseDescriptor:responseDescriptor];

    NSMutableURLRequest *urlRequest = [self.restKitObjectManager multipartFormRequestWithObject:ad method:RKRequestMethodPOST path:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

//        NSArray *photosArray = ad.photos[0];
//        for(int i = 0; i < photosArray.count; i++) {
//            
//            NSString *name = [NSString stringWithFormat:@"ad[photos_attributes][%i][picture]", i];
//            NSString *fileName = [NSString stringWithFormat:@"photo%i.jpg", i];
//            [formData appendPartWithFileData:UIImagePNGRepresentation(photosArray[i])
//                                        name:name
//                                    fileName:fileName
//                                    mimeType:@"image/jpg"];
//        }
    }];

    RKObjectRequestOperation *operation = [self.restKitObjectManager objectRequestOperationWithRequest:urlRequest
                                                                                               success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
                                                                                                   if ([self.serviceDelegate respondsToSelector:@selector(successfulRequestDidReturnObject:)])
                                                                                                       [self.serviceDelegate successfulRequestDidReturnObject:nil];

                                                                                               } failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                                                                                   if ([self.serviceDelegate respondsToSelector:@selector(requestDidFailWithError:)])
                                                                                                       [self.serviceDelegate requestDidFailWithError:error];
                                                                                               }];
    [self.restKitObjectManager enqueueObjectRequestOperation:operation];

    [self.restKitObjectManager removeRequestDescriptor:requestDescriptor];
    [self.restKitObjectManager removeResponseDescriptor:responseDescriptor];
}



- (NSDictionary *)adAttributes {
    return @{
             @"id" : @"_id",
             @"title" : @"title",
             @"price" : @"price",
             @"local" : @"local",
             @"description" : @"especification"
//             @"categories" : @"categories",
//             @"photos" : @"photos",
//             @"latitude" : @"latitude",
//             @"longitude" : @"longitude"
             };
}

- (NSDictionary *)postAdAttributes {
    return @{
             @"_id" : @"id",
             @"title" : @"title",
             @"price" : @"price",
             @"local" : @"local",
             @"especification" : @"description"
//             @"categories" : @"category_ids",
//             @"user_id" : @"user_id",
//             @"latitude" : @"latitude",
//             @"longitude" : @"longitude"
             };
}

- (NSDictionary *)userAttributes {
    return @{
             @"id" : @"_id",
             @"email" : @"email",
             @"name" : @"name",
             @"avatar" : @"profileImageUrl",
             @"phone" : @"phone",
             @"password" : @"password",
             @"contact_pref" : @"communicationPreference",
             @"products_alerts" : @"productsAlerts"
             };
}

- (NSDictionary *)postUserAttributes {
    return @{
             @"_id" : @"id",
             @"email" : @"email",
             @"name" : @"name",
             @"phone" : @"phone",
             @"password" : @"password",
             @"password" : @"password_confirmation",
             @"communicationPreference" : @"contact_pref"
             };
}
@end

这是我的 NewAdViewController:

#import "NewAdViewController.h"
#import "Ads.h"
#import "JVUtils.h"
#import "JVWebService.h"
#import "AppDelegate.h"

@interface NewAdViewController ()

@end

@implementation NewAdViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (IBAction)signUp:(id)sender {


    if (self.titleField.text.length <= 0) {
        [JVUtils showMessage:@"Falta algo ae eem =D =D fdp." withTitle:@"Opa!"];
    } else if (self.priceField.text.length <= 0) {
        [JVUtils showMessage:@"Falta algo ae eem =D =D fdp" withTitle:@"Opa!"];
    } else if (self.localField.text.length <= 0) {
        [JVUtils showMessage:@"Falta algo ae eem =D =D fdp" withTitle:@"Opa!"];
    } else if (self.descriptionField.text.length <= 0) {
        [JVUtils showMessage:@"Falta algo ae eem =D =D fdp" withTitle:@"Opa!"];
    } else {
            Ads *newAd = [Ads new];
            newAd.title = self.titleField.text;
            newAd.price = self.priceField.text;
            newAd.local = self.localField.text;
            newAd.especification = self.descriptionField.text;


            [[JVWebService sharedService] setServiceDelegate:self];
            [[JVWebService sharedService] postAd:newAd];

        }
    }


- (void)successfulRequestDidReturnObject:(NSObject *)object {

    [JVUtils showMessage:@"Anuncio cadastrado =D" withTitle:@"hadoukeeeen !"];

    [[AppDelegate sharedDelegate] setCurrentUser:(User *)object];

    [self dismissViewControllerAnimated:YES completion:nil];


}

- (void)requestDidFailWithError:(NSError *)error {

    [JVUtils showMessage:error.localizedDescription withTitle:@"Errohue"];
}


-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
}





@end

这是来自服务器日志的详细信息

Started POST "/ads.json" for 127.0.0.1 at 2015-03-03 18:06:15 -0300 Processing by AdsController#create as JSON Parameters: {"ad"=>{"description"=>"ewewe", "id"=>"", "local"=>"ew", "price"=>"25", "title"=>"titulp"}} User Load (0.6ms) SELECT users.* FROM users WHERE users.id = 2 ORDER BY users.id ASC LIMIT 1 Unpermitted parameters: id (0.2ms) BEGIN (0.6ms) ROLLBACK Completed 422 Unprocessable Entity in 10ms (Views: 0.3ms | ActiveRecord: 1.4ms)

状态代码 422 表示您的数据在某些方面不正确 - 请求格式正确但无法处理数据。

从服务器上看日志可以看到id是空的,有错误信息Unpermitted parameters: id

在发送请求之前,您需要确定 id 为空的原因并更正此问题。