0

i'm very new in iOS app development.I am going to use AFNetworking 3.0. On first view when i enter mobile no. and click on submit button then it connect with server and i get following response from server:

responseData: [{"edriverId":"bd307a3ec329e10a2cff8fb87480823da114f8f4","token":"6uc4d1houfecbmjgy9ezpru9n25nw40b17cwk439j52"}]

now my question is,how can i take only that token from responseData and send it to server from next view. Please help me.

NOTE:whenever we call service token changes every time.

my code is:

-(void)serverconnection

{

    NSString *Loginurl = [NSString stringWithFormat:@"https://24x7tracker.com/busservices/School/DriverPreLogin"];


NSDictionary *params = @{@"mobile":self.phonenumber.text,

                         @"archive":@"schooldb1"

                         };


AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];


manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];


manager.responseSerializer = [AFHTTPResponseSerializer serializer];

AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

[policy setValidatesDomainName:NO];

[policy setAllowInvalidCertificates:YES];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",nil];



manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",nil];


[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {


    NSLog(@"Json: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

    [self getdata:responseObject];


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

    [self performSegueWithIdentifier:@"loginsegue" sender:self];

}
      failure:^(NSURLSessionTask *operation, NSError *error)

{

    NSLog(@"Error: %@", error);

    UIAlertController *Erroralert=   [UIAlertController

                                      alertControllerWithTitle:@" Network Connection Failed!!"

                                      message:@"Please try again"

                                      preferredStyle:UIAlertControllerStyleAlert];

    [self presentViewController:Erroralert animated:YES completion:nil];





    UIAlertAction* yesButton = [UIAlertAction

                                actionWithTitle:@"Ok"

                                style:UIAlertActionStyleDefault

                                handler:^(UIAlertAction * action)

                                {
                                    [self resignFirstResponder];

                                    [Erroralert dismissViewControllerAnimated:YES completion:nil];



                                }];

    [Erroralert addAction: yesButton];


}];


}

-(void)getdata:(NSData *)data

{}
Suraj Sukale
  • 1,778
  • 1
  • 12
  • 19

3 Answers3

1

you can do this in two ways

  1. NSUserDefault

    // NSArray *temp = (NSArray *)responseObject;
    
    NSError *error;
    NSArray *temp = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
    
    [[NSUserDefaults standardUserDefaults] setObject:[[temp objectAtIndex:0] valueForKey:@"token"] forKey:@"token"];
    [self performSegueWithIdentifier:@"loginsegue" sender:self];
    

on second Page

Retrieve

for Retrieve the String in NSUserDefaults you can directly use objectForKey

NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
  1. Pass the string to second Page like

first page create one global value for store the object in string

@property (strong, nonatomic)          NSString *tokenString;

serilize the response object and store in the global value which one you need

                   NSError *error;
 NSArray *temp = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];

     // in this line we assingn the current value to global value
     tokenString = [[temp objectAtIndex:0] valueForKey:@"token"];
      [self performSegueWithIdentifier:@"loginsegue" sender:self];

on that destination view controller create one global value for pass the current string

@property (strong, nonatomic)          NSString *fetchtokenString;

on that first VC the prepareForSegue method pass the globalized value to second page

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

secondViewController *vc = segue.destinationViewController;
// pass the current object to second page value
vc.fetchtokenString = tokenString;

finally second VC you can get the value on viewDidload page

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
 NSLog (@"token value ==%@",fetchtokenString);
}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • @Anbu.Karthik...its not work..i got error like: - [_NSInlineData objectAtIndex:]: unrecognized selector sent to instance 0x7863f770 2016-05-18 11:42:11.185 BusTrkr[798:20925] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSInlineData objectAtIndex:]: unrecognized selector sent to instance 0x7863f770' – Suraj Sukale May 18 '16 at 06:14
  • @SurajSukale -- just wait I modify the answer – Anbu.Karthik May 18 '16 at 06:14
  • @SurajSukale - print this `NSArray *temp = (NSArray *)responseObject;` once bro – Anbu.Karthik May 18 '16 at 06:17
  • @Anbu.Karthik can you please explain me the second way to send value to another viewcontroller ..if you can ? – vaibhav May 18 '16 at 06:21
  • @vaibhav - in which line do u not understand – Anbu.Karthik May 18 '16 at 06:23
  • @Mahesh - I agree you reply , are you seen this `responseData: [{"edriverId":"bd307a3ec329e10a2cff8fb87480823da114f8f4","token":"6uc4d1houfecbmjgy9ezpru9n25nw40b17cwk439j52"}]`, it is start with array or dictionary bro – Anbu.Karthik May 18 '16 at 06:25
  • Hey friend @Anbu.Kartik ...i got again this error....-[_NSInlineData objectAtIndex:]: unrecognized selector sent to instance 0x7a1404a0 2016-05-18 11:53:29.410 BusTrkr[881:23878] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSInlineData objectAtIndex:]: unrecognized selector sent to instance 0x7a1404a0' – Suraj Sukale May 18 '16 at 06:25
  • actually i always used nsuserdefalut to pass values so i need to understand whole concept .. – vaibhav May 18 '16 at 06:26
  • @Anbu.Karthik.Please suggest me answer friend... i got error that in both case(using userdefault or in this also) – Suraj Sukale May 18 '16 at 06:32
  • @SurajSukale - problem in this line `NSArray *temp = (NSArray *)responseObject;` can you print the temp once what the output you got – Anbu.Karthik May 18 '16 at 06:33
  • @SurajSukale did you check your response is not in valid json format ? – vaibhav May 18 '16 at 06:33
  • @vaibhav - the json is valid bro, if sukale print the temp object we can get the output – Anbu.Karthik May 18 '16 at 06:35
  • @Anbu.Karthik.... i got that error and on the line _tokenString = [[temp objectAtIndex:0] valueForKey:@"token"]; it shows like ...... signal SIGABRT – Suraj Sukale May 18 '16 at 06:43
  • @SurajSukale - just print the `temp` result – Anbu.Karthik May 18 '16 at 06:44
  • @SurajSukale use code **NSDictionary *dict = [returnString JSONValue]; NSString *status = [dictMain valueForKey:@"token"];** **you need to use SBJson lib to call JSONValue method** if you comfortable to use NSDictionary .. – vaibhav May 18 '16 at 06:45
  • @Anbu.Karthik......temp result is like this..... temp=<5b7b2265 64726976 65724964 223a2262 64333037 61336563 33323965 31306132 63666638 66623837 34383038 32336461 31313466 38663422 2c22746f 6b656e22 3a22787a 7a626d76 6f697977 6376327a 336c6e31 6361656d 6c637773 746c666b 6b626968 71613469 62377865 36227d5d> – Suraj Sukale May 18 '16 at 07:02
  • @Anbu.Karthik...please see this question.... http://stackoverflow.com/questions/37315226/how-to-send-background-location-to-server-periodically-if-location-change-or-not/37315807#37315807 – Suraj Sukale May 19 '16 at 07:32
0

You can do as follow

Parse ur response like this

 NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject];

Get your token in one global variable suppose

NSString *token = [json objectForkey:@"token"];

When you push next UIViewController, set this value as property of next UIViewController. For that, you need to create one property of type NSString in next UIViewController like:

@property(nonatomic, copy) NSString *token;

Access that propery in first UIViewController like this. You have to add following line before pushing the next UIViewControler

sectionViewControllerObject.token = token //variable of first UIViewController
Yunus Nedim Mehel
  • 12,089
  • 4
  • 50
  • 56
user3306145
  • 76
  • 2
  • 12
0

@Anbu.Karthik if you want to send the value from First view controller to Second view controller then you can do in many of ways either you can use segue or delegate or NSnotification.

I am doing in swift for only getting the token data just try this using objective C.

var myArray: NSMutableArray = [["edriverId":"1234","token":"anytokenid"]]

print(myArray)

var parsedata:String = myArray.objectAtIndex(0).valueForKey("token")as!String

print(parsedata)
Suraj Sukale
  • 1,778
  • 1
  • 12
  • 19
Sanjeet Verma
  • 551
  • 4
  • 15