Suraj Sukale Suraj Sukale - 1 year ago 47
iOS Question

How to save response and send specific parameter in that response to server using AFN 3.0?

I am going to use

AFNetworking 3.0

On my first view when i enter mobile number and click on submit button then it send to server and get response from server, in that response, suppose i get 2 parameters ( like id:xx, token:xxxxx,).

Now my question is-

When i get response from server then i want to go on 2nd view and when i click on login button,I want to send only token which i got from previous response(not id).How can i take only that token from previous view and send it from current view.

I tried like this,but it not completed or not working.
I tried to save response data like this:

NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"responseData: %@", str);

and tried to send on 2nd view:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier]isEqualToString:@"loginsegue"])
loginViewController *lvc= [segue destinationViewController];

Answer Source

AFNetworking is well transforming JSON data to an id type in iOS . You just need to convert it based on your response.

Generally it can be done like this e.g.

NSDictionary *response = (NSDictionary *)responseObject;
NSString *token = [response valueForKey:@"token"];
//Save token some where to use it later.

Once, you have this token you can

  1. Store it some where, may be NSUserDefaults (Not recommended, but easy way).
  2. Then whenever you need to require to pass on that token, you should fetch it (wherever you've stored), in our case NSUserDefaults, and send it to server.

Please Note: If your token is changing every time then, you can store it for temporary (may be singleton) and use it whenever needed. As long as, you may require token inside any view controller, you should not pass it to each view controller. Better to make it globally available.