use like this.....
Create file
#import <Foundation/Foundation.h>`
#import "SharedManager.h"
#import "Constant.h"
#import "UserDetails.h"
@interface APISession : NSURLSession<NSURLSessionDelegate>
@property (nonatomic, retain) NSMutableData *responseData;
+(void)postRequetsWithParam:(NSMutableDictionary* )objDic withAPIName:(NSString*
)strAPIURL completionHandler:(void (^)(id result, BOOL status))completionHandler;
@end
****************.m*************************
#import "APISession.h"
#import <UIKit/UIKit.h>
@implementation APISession
+(void)postRequetsWithParam:(NSMutableDictionary *)objDic withAPIName:(NSString
*)strAPIURL completionHandler:(void (^)(id, BOOL))completionHandler
{
NSURL *url=[NSURL URLWithString:strAPIURL];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *err = nil;
NSData *data=[NSJSONSerialization dataWithJSONObject:objDic options:NSJSONWritingPrettyPrinted error:&err];
[request setHTTPBody:data];
NSString *strJsonFormat = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"API URL: %@ \t Api Request Parameter ::::::::::::::%@",url,strJsonFormat);
// NSLog(@"Request data===%@",objDic);
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
// NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
if (error==nil) {
NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];\
NSLog(@"Response Data=============%@",dicData);
if([[dicData valueForKey:@"tokenExpired"]integerValue] == 1)
{
NSLog(@"hello");
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"Access Token Expire." forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"UserLogOut" object:self userInfo:dict];
}
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(dicData,(error == nil));
});
NSLog(@"%@",dicData);
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(error.localizedDescription,NO);
});
}
}];
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[task resume];
// });
}
@end
*****************************in .your view controller***********
#import "file"
txtEmail.text = [txtEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
{
[SVProgressHUD showWithStatus:@"Loading..."];
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
NSMutableDictionary *objLoginDic=[[NSMutableDictionary alloc] init];
[objLoginDic setValue:txtEmail.text forKey:@"email"];
[objLoginDic setValue:@0 forKey:kDeviceType];
[objLoginDic setValue:txtPassword.text forKey:kPassword];
[objLoginDic setValue:@"376545432" forKey:kDeviceTokan];
[objLoginDic setValue:@"" forKey:kcountryId];
[objLoginDic setValue:@"" forKey:kfbAccessToken];
[objLoginDic setValue:@0 forKey:kloginType];
[APISession postRequetsWithParam:objLoginDic withAPIName:KLOGIN_URL completionHandler:^(id result, BOOL status) {
[SVProgressHUD dismiss];
NSInteger statusResponse=[[result valueForKey:kStatus] integerValue];
NSString *strMessage=[result valueForKey:KMessage];
if (status) {
if (statusResponse == 1)
{
UserDetails *objLoginUserDetail=[[UserDetails alloc]
initWithObject:[result valueForKey:@"userDetails"]];
[[NSUserDefaults standardUserDefaults]
setObject:@(objLoginUserDetail.userId) forKey:@"user_id"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self clearTextfeilds];
HomeScreen *obj=[Kiran_Storyboard instantiateViewControllerWithIdentifier:@"HomeScreen"];
[self.navigationController pushViewController:obj animated:YES];
}
else{
[strMessage showAsAlert:self];
}
}
}];
}
**********use model class for represnt data*************
#import <Foundation/Foundation.h>
#import "Constant.h"
#import <objc/runtime.h>
@interface UserDetails : NSObject
@property(strong,nonatomic) NSString *emailId,
*deviceToken,
*countryId,
*fbAccessToken,
*accessToken,
*countryName,
*isProfileSetup,
*profilePic,
*firstName,
*lastName,
*password;
@property (assign) NSInteger userId,deviceType,loginType;
-(id)initWithObject :(NSDictionary *)dicUserData;
-(void)saveLoginUserDetail;
+(UserDetails *)getLoginUserDetail;
-(UserDetails *)getEmptyModel;
- (NSArray *)allPropertyNames;
-(void)printDescription;
-(NSMutableDictionary *)getDictionary;
@end
******************model.m*************
#import "UserDetails.h"
#import "SharedManager.h"
@implementation UserDetails
-(id)initWithObject :(NSDictionary *)dicUserData
{
self = [[UserDetails alloc] init];
if (self)
{
@try {
[self setFirstName:([dicUserData valueForKey:@"firstName"] != [NSNull null])?
[dicUserData valueForKey:@"firstName"]:@""];
[self setUserId:([dicUserData valueForKey:kUserId] != [NSNull null])?
[[dicUserData valueForKey:kUserId] integerValue]:0];
}
@catch (NSException *exception) {
NSLog(@"Exception: %@",exception.description);
}
@finally {
}
}
return self;
}
-(UserDetails *)getEmptyModel{
[self setFirstName:@""];
[self setLastName:@""];
[self setDeviceType:0];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
// Encode properties, other class variables, etc
[encoder encodeObject:_firstName forKey:kFirstName];
[encoder encodeObject:[NSNumber numberWithInteger:_deviceType] forKey:kDeviceType];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
_firstName = [decoder decodeObjectForKey:kEmailId];
_deviceType= [[decoder decodeObjectForKey:kDeviceType] integerValue];
}
return self;
}
- (NSArray *)allPropertyNames
{
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray *rv = [NSMutableArray array];
unsigned i;
for (i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}
free(properties);
return rv;
}
-(void)printDescription{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for(NSString *key in [self allPropertyNames])
{
[dic setValue:[self valueForKey:key] forKey:key];
}
NSLog(@"\n========================= User Detail ==============================\n");
NSLog(@"%@",[dic description]);
NSLog(@"\n=============================================================\n");
}
-(NSMutableDictionary *)getDictionary{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for(NSString *key in [self allPropertyNames])
{
[dic setValue:[self valueForKey:key] forKey:key];
}
return dic;
}
#pragma mark
#pragma mark - Save and get User details
-(void)saveLoginUserDetail{
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self];
[Shared_UserDefault setObject:encodedObject forKey:kUserDefault_SavedUserDetail];
[Shared_UserDefault synchronize];
}
+(UserDetails *)getLoginUserDetail{
NSData *encodedObject = [Shared_UserDefault objectForKey:kUserDefault_SavedUserDetail];
UserDetails *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
@end
************************usefull code while add data into model and get data********
NSLog(@"Response %@",result);
NSString *strMessg = [result objectForKey:kMessage];
NSString *status = [NSString stringWithFormat:@"%@",[result
objectForKey:kStatus]];
if([status isEqualToString:@"1"])
{
arryBankList =[[NSMutableArray alloc]init];
NSMutableArray *arrEvents=[result valueForKey:kbankList];
ShareOBJ.isDefaultBank = [result valueForKey:kisDefaultBank];
if ([arrEvents count]>0)
{
for (NSMutableArray *dic in arrEvents)
{
BankList *objBankListDetail =[[BankList alloc]initWithObject:[dic
mutableCopy]];
[arryBankList addObject:objBankListDetail];
}
//display data using model...
BankList *objBankListing =[arryBankList objectAtIndex:indexPath.row];