Search code examples
iosobjective-cafnetworking

How to add headers in AFNetworking 4.0 in POST Request?


I am doing this for defining headers in AFNetworking 4.0

      NSMutableDictionary *headers = [[NSMutableDictionary alloc]init];
      [headers setValue:[NSString stringWithFormat:@"Bearer %@",[defaults valueForKey:@"Token"]]  forKey:@"Authorization"];
      [manager POST:[NSURL URLWithString:path].absoluteString parameters:parameter headers:headers progress:nil success:^(NSURLSessionTask *task, id responseObject)
         { 

          }

And this is the method new POST method define in AFNetworking 4.0

    - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                   URLString:(NSString *)URLString
                                  parameters:(nullable id)parameters
                                     headers:(nullable NSDictionary <NSString *, NSString *> *)headers
                              uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                            downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                     success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                     failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
     { 

      }

While doing This is showing me error "[<__NSDictionary0 0x10c62a870> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Authorization."

Please tell me correct solution for this.

Thanks in Advance.


Solution

  • From the Above Given Answers I found a midway for the answers. Thanks for the Response @baiyidjp and @Silversky Technology

         AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
         [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    
         NSString *path=[[NSString alloc]initWithFormat:@"%@",URL];
    
         NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
         [parameter setValue:@"123456" forKey:@"id"];
    
         NSDictionary *headers = @{@"Authorization":[NSString stringWithFormat:@"Bearer %@",[defaults valueForKey:@"ApiToken"]]};
    
          [manager POST:[NSURL URLWithString:path].absoluteString parameters:parameter headers:headers progress:nil success:^(NSURLSessionTask *task, id responseObject)
             {
              NSLog(@"Response Object response is....==%@",responseObject);
              }
                  failure:^(NSURLSessionTask *operation, NSError *error)
             {
              NSLog(@"Error Last 2 Done: %@", [error localizedDescription]);
              }