简体   繁体   中英

How to save the response From My server , and How can i access That data

Hi i am getting the response from my server successfully.i need to access the user_id send by the server in my app.

check my code:

 NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];



        NSURL * url = [NSURL URLWithString:@"my url"];
        NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];




        NSString * params=[[NSString alloc]initWithFormat:@"mobile=%@",[self.reqnum text ]];

        NSLog(@"%@",params);
        [urlRequest setHTTPMethod:@"POST"];
        [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

        NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                           completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                               NSLog(@"Response:%@ %@\n", response, error);
                                                               if(error == nil)
                                                               {
                                                                   NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

                                                                     NSLog(@"Data = %@",text);



                                                                   [[NSUserDefaults standardUserDefaults]setObject:@"Y" forKey:@"login"];

                                                                   [[NSUserDefaults standardUserDefaults] synchronize];


                                                               }


                                                           }];
        [dataTask resume];

for this code i am getting the response like:

here i need to access the user_id in my app .so can i get that particular user_id.

Thank You.

If you want to use the value in other classes then :

First create a data Model Class, parse the data dictionary/JSON and store it. Using the completion block you can return the specific/received user_id to the caller.

Here you are getting in JSON, you can parse it and get the desired data:

NSDictionary *respDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSString *userID = respDict[@"user_id"];

Since original solutions have already been posted, I will focus on longer & more tedious way which I think is the proper way to handle the elephant in the room. This will help you in the longer run.

Create a Singleton class since there can be only one user logged in at one time.

SharedUser.h

#import <Foundation/Foundation.h>
@interface SharedUser : NSObject

@property (strong, nonatomic) NSString* userId;
@property (strong, nonatomic) NSString* userName;
@property (strong, nonatomic) NSString* subscriptionStatus;
@property (strong, nonatomic) NSString* registerDate;
@property (strong, nonatomic) NSString* expiryDate;
+(SharedUser*) getInstance;

@end

SharedUser.m

#import "SharedUser.h"

@implementation SharedUser



static SharedUser * sharedInstance;



+(SharedUser*) getInstance
{
    @synchronized(self)
    {
        if(sharedInstance == nil)
        {

            sharedInstance = [[SharedUser alloc] init];
            sharedInstance.userName = @"";
            sharedInstance.userId = @"";
            sharedInstance.subscriptionStatus = @"";
            sharedInstance.registerDate = @"";
            sharedInstance.expiryDate = @"";
            return sharedInstance;
        }
        else
        {
            return  sharedInstance;
        }

    }
}

Convert your response into NSDictionary .

NSDictionary *json_dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];;//From Santosh Reddy's Answer

Populate your sharedInstance with the result attributes:

[SharedUser getInstance].userId = [json_dict objectForKey:@"user_id"];
[SharedUser getInstance].userName = [json_dict objectForKey:@"username"];
[SharedUser getInstance].subscriptionStatus = [json_dict objectForKey:@"subscription_status"];
[SharedUser getInstance].registryDate = [json_dict objectForKey:@"register_date"];//Better to use NSDate type instead of NSString
[SharedUser getInstance].expiryDate = [json_dict objectForKey:@"expiry_date"];

Now your user's attributes will be available anywhere in the App. You just need to import SharedUser.h to desired UIView , UIViewController & type following to access your data:

NSString *userId = [SharedUser getInstance].userId;

Also Note that I am using singleton pattern because I am assuming that you only need to handle one user's attributes which will be used in multiple viewcontrollers over the span of time. If you need multiple users saved, create a similar user model class and populate them in a similar way. (Just don't make them singleton).

Also I would suggest that you should read Ray Wenderlich's series tutorials on:

1. Object Oriented Design
2. Design Patterns
3. Intro to iOS design patterns

The response is a JSON object. If what you are asking is how to parse it, then there is an inbuilt JSON parser in iOS.

NSDictionary *json_dict = [text JSONValue];
NSString *userID = [result objectForKey:@"user_id"];

Create a NSDictionary to get json data.

   NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     NSLog(@"Response:%@ %@\n", response, error);
     if(error == nil)
             {
      NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
      NSString *userID = [dictionary objectForKey:@"user_id"];
}

 }];

Yes, its upto you how to store data and if you want to parse it, then try

NSDictionary *jsonDict = [responseString JSONValue];
NSString *user_id = [jsonDict objectForKey:@"user_id"];

Parse the data that you're getting in block as below.

completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     NSLog(@"Response:%@ %@\n", response, error);
     if(error == nil)
             {
     NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSDictionary *response = JSON[@"user_id"];
}

 }];

You can make a NSDictionary, save JSON data in it and fetch user_id from it. Like this:

NSDictionary *dictionaryName=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSString *user_id= [dictionaryName valueForKey:@"user_id"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM