Ad

How To Save The Response From My Server , And How Can I Access That Data

- 1 answer

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.

Ad

Answer

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

Ad
source: stackoverflow.com
Ad