How to save the response From My server , and How

2020-07-20 03:49发布

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.

7条回答
祖国的老花朵
2楼-- · 2020-07-20 04:22

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

查看更多
乱世女痞
3楼-- · 2020-07-20 04:24

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"];
查看更多
冷血范
4楼-- · 2020-07-20 04:31

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"];
}

 }];
查看更多
Rolldiameter
5楼-- · 2020-07-20 04:32

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"];
查看更多
够拽才男人
6楼-- · 2020-07-20 04:37

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"];
}

 }];
查看更多
太酷不给撩
7楼-- · 2020-07-20 04:40

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"];
查看更多
登录 后发表回答