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

Posted

技术标签:

【中文标题】NSLocalizedDescription=(200-299)中的预期状态码,得到 422【英文标题】:NSLocalizedDescription=Expected status code in (200-299), got 422 【发布时间】:2015-03-03 21:14:15 【问题描述】:

我正在尝试发布广告。我按照我认为正确的方式设置了所有内容,但是当我单击玻色子“地籍 anuncio”时,它返回此错误“得到 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

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

在 2015-03-03 18:06:15 -0300 为 127.0.0.1 开始 POST "/ads.json" AdsController#create 作为 JSON 参数处理: "ad"=>"description"=>"ewewe", "id"=>"", "local"=>"ew", "price"=>"25", "title"=>"titulp" 用户负载 (0.6ms) SELECT users.* FROM users WHERE users.id = 2 ORDER BY users.id ASC LIMIT 1 不允许的参数:id (0.2ms) BEGIN (0.6ms) ROLLBACK Completed 10 毫秒内出现 422 个无法处理的实体(查看次数:0.3 毫秒 | ActiveRecord:1.4 毫秒)

【问题讨论】:

422 表示您的数据在某些方面不正确 - 您应该检查您的服务器日志以查看是否有更多信息可用。也许密码不符合复杂性要求? 我没有添加使用密码的对象。我正在注册一个包含描述和价格标题的简单公告。作为销售申请编号。我在注册用户时使用了类似的方法。我认为这是问题,但似乎没有找到解决方法。 对不起,我没有意识到 - 你已经发布了很多代码 - 我看到了第一个发布操作是用户。将来最好将您的问题简化为仅包含 相关 代码,但是我的建议仍然有效 - 422 表示服务器对您发送的数据不满意。您需要检查您发送的值并在服务器日志中查找更多详细信息 于 2015-03-03 18:06:15 -0300 开始 POST "/ads.json" for 127.0.0.1 由 AdsController#create 作为 JSON 参数处理:"ad"=>" description"=>"ewewe", "id"=>"", "local"=>"ew", "price"=>"25", "title"=>"titulp" 用户负载 (0.6ms) SELECT users.* FROM users WHERE users.id = 2 ORDER BY users.id ASC LIMIT 1 不允许的参数:id (0.2ms) BEGIN (0.6ms) ROLLBACK Completed 422 Unprocessable在 10 毫秒内(查看:0.3 毫秒 | ActiveRecord:1.4 毫秒) 这是来自服务器的响应。你能理解吗?到目前为止,我能理解的内容对我没有多大帮助。 【参考方案1】:

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

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

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

【讨论】:

以上是关于NSLocalizedDescription=(200-299)中的预期状态码,得到 422的主要内容,如果未能解决你的问题,请参考以下文章

AFNetworking 问题:NSErrorFailingURLKey=url,NSLocalizedDescription=请求失败:错误请求 (400)

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

如何 NSException 获取本地化的 NSLocalizedDescription

带有 AFNetworking 的 iOS POST:NSLocalizedDescription=请求失败:内部服务器错误 (500)

获取不到设备token NSLocalizedDescription=remote notifications are not supported in the simulator

如何将新数据保存到现有单元格?