无法使用 afnetworking 注册用户

unable to register an user using afnetworking

我想创建一个用户到后端服务器,我需要输入以下信息来注册用户。

 {
  "user": {
    "email": "user@example.com",
    "password": "secret",
    "password_confirmation": "secret",
    "seed_recipes": true                 //optional
  }

我写了下面的代码来注册用户:

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary *parameters = @{@"user[email]":email, @"user[password]":password, @"user[password_confirmation]":password};
    [manager POST:@"http://domain.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);

我遇到了以下错误。有没有人知道原因? (JSON 文本未以数组或对象开头,并且未设置允许片段的选项。)UserInfo=0x7fbe935cb360 {NSDebugDescription=JSON 文本未以数组或对象开头,并且未设置允许片段的选项。 , NSUnderlyingError=0x7fbe935c54b0 "Request failed: unauthorized (401)"}

可能您的服务器没有响应 JSON 格式,只是纯 HTML。

尝试添加:

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

如果这没有帮助,请确保您的服务器以 [​​=18=] 格式响应您尝试创建的 POST。

NSDictionary *users=[[NSDictionary alloc] initWithObjects:@{@"email":email, @"password":password, @"password_confirmation":password}];

NSDictionary *parameters = [[NSDictionary alloc] initWithObjects:@{@"user":users}];

试试这个