Why does authentication not work with my ASP.NET REST API? - ios

I setup an ASP.NET REST API, and am trying to connect through iOS. The same error continues to appear, and I am not sure where the connection is "broken". In NSLog the link appears with both slashes rather than a forward slash as is in the NSString. Can anyone show me why this is not connecting?
Completion block log:
2015-02-08 23:19:00.795 b2bGatewayWebview[7266:548905] Loading... ["method","interface","parameters","UserAuthentication","http:\/\/website.com\/folder\/Handler1.ashx",{"userName":"DummyAcct","passsword":"DummyPwd"}]
2015-02-08 23:19:00.796 b2bGatewayWebview[7266:548905] Loading... {"method":"Getmembers","interface":"http:\/\/website.com\/folder\/Handler1.ashx","parameters":{"username":"DummyAcct"}}
2015-02-08 23:19:00.795 b2bGatewayWebview[7266:548861] View did load called.
2015-02-08 23:19:01.525 b2bGatewayWebview[7266:548937] done
2015-02-08 23:19:01.537 b2bGatewayWebview[7266:548937] RAW response = {
"Successful": false,
"ErrorMessage": "Internal server error"
}
RestAPI.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#interface RestAPI: UIViewController
#property (nonatomic, strong) NSURL *url;
#property (nonatomic, strong) NSString *interface;
-(void) CreateNewAccount:(NSString*)ausername password:(NSString*)apassword completionHandler:(void(^)(NSDictionary *dictionary, NSError *error))handler;
-(void) Getmembers:(NSString*)ausername completionHandler:(void(^)(NSDictionary *dictionary, NSError *error))handler;
-(void) UserAuthentication:(NSString*)auserName passsword:(NSString*)apasssword completionHandler:(void(^)(NSDictionary *dictionary, NSError *error))handler;
#end
RestAPI.m
#import "RestAPI.h"
#implementation RestAPI
#synthesize url;
#synthesize interface;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *initialLink = #"http://website.com/Handler1.ashx";
[self setInterface:initialLink];
NSString *username = #"DummyAcct";
NSString *password = #"DummyPswd";
//asynchronously call login method
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self UserAuthentication:username passsword:password completionHandler:^(NSDictionary *dictionary, NSError *error) {
NSLog(#"Login method called.");
}];
[self Getmembers:username completionHandler:^(NSDictionary *dictionary, NSError *error) {
nil;
}];
});
NSLog(#"View did load called.");
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (id) init
{
self = [super init];
if (self) {
[self setUrl: [NSURL URLWithString: #"http://website.com/Handler1.ashx"]];
[self setInterface:#"http://website.com/Handler1.ashx"];
}
return self;
}
- (void)load:(NSData*)data completionHandler:(void(^)(NSURLResponse *response, NSData *data, NSError *error))handler
{
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Loading... %#", s);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue
completionHandler:handler];
}
- (void) Getmembers:(NSString*)ausername completionHandler:(void(^)(NSDictionary *dictionary, NSError *error))handler
{
NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:interface forKey:#"interface"];
[d setValue:#"Getmembers" forKey:#"method"];
NSMutableDictionary *p = [[NSMutableDictionary alloc] init];
[p setValue:ausername forKey:#"username"];
[d setValue:p forKey:#"parameters"];
NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
[self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"done");
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"RAW response = %#", s);
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
handler(d, error);
}];
}
//login method
-(void) UserAuthentication:(NSString*)auserName passsword:(NSString*)apasssword completionHandler:(void(^)(NSDictionary *dictionary, NSError *error))handler
{
//NSMutableArray *a = [[NSMutableArray alloc] init];
NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:interface forKey:#"interface"];
//[a setValue:interface forKey:#"interface"];
[d setValue:#"UserAuthentication" forKey:#"method"];
//[a setValue:#"UserAuthentication" forKey:#"method"];
NSMutableDictionary *p = [[NSMutableDictionary alloc] init];
[p setValue:auserName forKey:#"userName"];
[p setValue:apasssword forKey:#"passsword"];
[d setValue:p forKey:#"parameters"];
//[a setValue:p forKey:#"parameters"];
NSMutableArray *dictAllKeys=[NSMutableArray arrayWithArray:[d allKeys]];
NSMutableArray *dictAllValues=[NSMutableArray arrayWithArray:[d allValues]];
NSMutableArray *keysAndValues=[NSMutableArray arrayWithArray:[dictAllKeys arrayByAddingObjectsFromArray:dictAllValues]];
//NSJSONWritingOptions *writingOptions;
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:keysAndValues options:0 error:&error];
[self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"done");
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"RAW response = %#", s);
//NSJSONReadingOptions *options;
NSError *error2;
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error2];
handler(d, error);
}];
}
#end

The Rest API SQL settings were incorrect (Integrated Security was true). Also on the iOS side, I should not have been passing an array for user authentication, but a dictionary.

Related

Obtaining an JSON Token using Authentication in Objective-C

Hi fairly new to iOS just trying to connect the app to an API and get my token using Authentication. I have tried a lot of different options and just can't seem to get my head around it. All i'm trying to do is obtain my token. Can anyone see where I'm going wrong? The API documentation is here: https://simplybook.me/en/api/developer-api
NSURL *url = [NSURL URLWithString:#"http://user-api.simplybook.me/login/"];
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"myloginname" forHTTPHeaderField:#"X-Company-Login"];
[request setValue:#"mytokenhere" forHTTPHeaderField:#"X-Token"];
NSURLSessionDataTask *downloadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray * resultDict =[json objectForKey:#"name"];
NSLog(#"%#", resultDict);
} else {
NSLog(#"%#", error);
}
}];
[downloadTask resume];
Instead of declaring NSURLSession like this:
NSURLSession *session = [NSURLSession sharedSession];
Try this instead:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://user-api.simplybook.me/login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
And also, make sure you've declared the NSURLSessionDelegate protocol in your header file.
I will give you sample code for getting token but this is regarding to the access and refresh token.You can understand it very clearly now.
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)actionLogin:(id)sender {
[self loginForGettingAccessandRefreshToken];
}
-(void)loginForGettingAccessandRefreshToken
{
#try {
NSString *strUserName = [textUsername.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *strPassword = [textPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *strParameters = [NSString stringWithFormat:#"client_id=roclient&client_secret=secret&grant_type=password&username=%#&password=%#&scope=dataEventRecords offline_access", strUserName, strPassword];
id param = strParameters;
NSLog(#"The param is - %#",param);
[GlobalShareClass postLoginDataToServer:BASEURL_LOGIN passParameters:param success:^(id res)
{
if([res isKindOfClass:[NSDictionary class]]){
NSDictionary *dictRes = [res copy];
NSString *strErrDesc = [NSString stringWithFormat:#"%#",[dictRes objectForKey:#"error_description"]];
if([[dictRes allKeys] containsObject:#"error_description"]){
dispatch_async(dispatch_get_main_queue(), ^{
//Dispaly UI
});
}
else{
NSString *strAccessToken = [dictRes objectForKey:#"access_token"];
NSString *strRefreshToken = [dictRes objectForKey:#"refresh_token"];
NSString *strTokenType = [dictRes objectForKey:#"token_type"];
NSString *sstrExpiresIn = [dictRes objectForKey:#"expires_in"];
[[NSUserDefaults standardUserDefaults] setObject:globalShare.strRefreshToken forKey:#"refresh_token"];
[[NSUserDefaults standardUserDefaults] setObject:globalShare.strAccessToken forKey:#"access_token"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSDictionary *responseDict = [GlobalShareClass getDataFromToken:globalShare.strAccessToken];
NSString *strFetchedSub = [[NSUserDefaults standardUserDefaults] stringForKey:#"loginIdSub"];
globalShare.loginId = [responseDict objectForKey:#"sub"];
}
}
else{
NSLog(#"The res starts with array");
}
} failure:^(NSError *error) {
// error handling here ...
NSLog(#"%#", [error localizedDescription]);
dispatch_async(dispatch_get_main_queue(), ^{
//Showing Error
});
} passViewController:self];
}
#catch(NSException *exception){
NSLog(#"%#",[exception description]);
}
#finally{
}
}
}
GlobalShareClass.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface GlobalShareClass : NSObject{
NSMutableArray *arr;
}
#property (strong, nonatomic) NSMutableArray *arr;
+ (GlobalShareClass *)sharedInstance;
+ (void)postLoginDataToServer:(NSString *)url passParameters:(id)parameter success:(void (^)(id res))successPost failure:(void(^)(NSError* error))failurePost passViewController:(UIViewController *)vc;
+ (NSDictionary *)getDataFromToken:(NSString *)strToken;
+ (NSDictionary *)urlBase64Decode:(NSString *)strToParse;
#end
GlobalShareClass.m
#import "GlobalShareClass.h"
#implementation GlobalShareClass
#synthesize arr;
+ (GlobalShareClass *)sharedInstance {
static GlobalShareClass* _shareInstane = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shareInstane = [[GlobalShareClass alloc] init];
//Incase array of initialization
_shareInstane.arr = [[NSMutableArray alloc] init];
});
return _shareInstane;
}
+ (void)postLoginDataToServer:(NSString *)url passParameters:(id)parameter success:(void (^)(id res))successPost failure:(void(^)(NSError* error))failurePost passViewController:(UIViewController *)vc{
GlobalShareClass *globalShare = [GlobalShareClass sharedInstance];
__block id jsonResp;
NSData *data = [parameter dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data == nil && error){
NSLog(#"uploadTaskWithRequest error: %#", error);
failurePost(error);
}
else{
jsonResp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *strStatusCode = [NSString stringWithFormat:#"%ld",(long)[((NSHTTPURLResponse *)response) statusCode]];
if([strStatusCode isEqualToString:#"400"]){
successPost(jsonResp);
}
NSString *strStatusCodeResponse = [self strGetStatusResponseCode:strStatusCode];
if([strStatusCodeResponse length] > 0){
dispatch_async(dispatch_get_main_queue(), ^{
// Showing error
});
}else{
jsonResp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if([jsonResp objectForKey:#"error"] || jsonResp == nil){
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlertController:#"Error" :[jsonResp objectForKey:#"error_description"] passViewController:vc];
});
}
else
successPost(jsonResp);
}
}
}];
[dataTask resume];
}
+ (NSDictionary *)getDataFromToken:(NSString *)strToken {
NSDictionary *data;
NSString *encoded = [strToken componentsSeparatedByString:#"."][1];
data = [GlobalShareClass urlBase64Decode:encoded];
return data;
}
+ (NSDictionary *)urlBase64Decode:(NSString *)strToParse {
#try {
NSDictionary *returnDict;
NSString *output = [strToParse stringByReplacingOccurrencesOfString:#"-" withString:#"+"];
output = [output stringByReplacingOccurrencesOfString:#"_" withString:#"/"];
switch (output.length % 4) {
case 0:
case 1:
break;
case 2:
output = [output stringByAppendingString:#"=="];
break;
case 3:
output = [output stringByAppendingString:#"="];
break;
default:
break;
}
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:output options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"%#", decodedString);
NSData *data = [decodedString dataUsingEncoding:NSUTF8StringEncoding];
returnDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
return returnDict;
}
#catch (NSException *exception) {
NSLog(#"%#", [exception description]);
}
}
#end

How can I make a request to aws cloudsearch using the AWS iOS SDK?

I have a client that runs their search functionality on their website through cloudsearch. I have been going through the documentation for days, and haven't been able to make a successful search request. I created an NSMutableRequest object, and am running that request through the AWSSignature method [signature interceptRequest:request]; but my task.result is coming back (null).
Here is my code:
AWSTask *task = [signature interceptRequest:request];
[task continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) {
NSLog(#"task.result fromSearch:%#", task.result);
NSData *responseData = task.result;
NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"newStr:%#", newStr);
NSLog(#"task.error:%#", task.error);
return nil;
}];
Am I on the right track, or is there a better way to do this through the aws iOS sdk?
To put a little more flesh on the bones of Robert's comment, I did it with some help from AFNetworking like so:
#import <AWSCore/AWSSignature.h>
#import <AWSCore/AWSService.h>
#import <AWSCore/AWSCategory.h>
#import <AWSCore/AWSCredentialsProvider.h>
#import <AWSCore/AWSTask.h>
#import "AFNetworking.h"
- (void)viewDidLoad {
[super viewDidLoad];
self.queue = [[NSOperationQueue alloc] init];
}
- (void)performSearch {
AWSAnonymousCredentialsProvider* credentialsProvider = [[AWSAnonymousCredentialsProvider alloc] init];
NSString* searchHost = #"<CloudSearchEndPoint>.eu-west-1.cloudsearch.amazonaws.com";
NSString* query = [self.searchTerms aws_stringWithURLEncoding];
NSURL* searchURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://%#/2013-01-01/search?q=%#", searchHost, query]];
AWSEndpoint* endpoint = [[AWSEndpoint alloc] initWithURL:searchURL];
AWSSignatureV4Signer* signer = [[AWSSignatureV4Signer alloc] initWithCredentialsProvider:credentialsProvider endpoint:endpoint];
NSMutableURLRequest* mutableRequest = [[NSMutableURLRequest alloc] initWithURL:searchURL];
AWSTask* task = [signer interceptRequest:mutableRequest];
[task continueWithBlock:^id(AWSTask* _Nonnull t) {
if (t.error) {
NSLog(#"Error: %#", t.error);
} else if (t.completed) {
NSLog(#"Result is %#", t.result);
}
AFJSONRequestOperation* operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:mutableRequest success:^(NSURLRequest* request, NSHTTPURLResponse* response, id JSON) {
NSLog(#"Success fetching results!");
if (JSON) {
NSDictionary* hitsContainer = [JSON objectForKey:#"hits"];
NSArray* hits = [hitsContainer objectForKey:#"hit"];
NSMutableArray* allResults = [[NSMutableArray alloc] initWithCapacity:hits.count];
for (NSDictionary* hit in hits) {
NSDictionary* fields = [hit objectForKey:#"fields"];
[allResults addObject:fields];
}
self.searchResults = allResults;
[self.tableView reloadData];
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Failure fetching search results :-( %#", error);
}
];
[self.queue addOperation:operation];
return nil;
}];

how do i create my array dynamically where values fetching from json in ios

-(IBAction)DropDownPressed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://rest-service.guides.spring.io/greeting"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray * array = [greeting objectForKey:#"id"];
NSLog(# "%#",array);
ibtn=0;
[Dropobj fadeOut];
[self showPopUpWithTitle:#"Select Country" withOption:arryList xy:CGPointMake(16, 58) size:CGSizeMake(287, 330) isMultiple:NO];
}
}
];
}
- (void)viewDidLoad {
[super viewDidLoad];
arryList=[[NSArray alloc] initWithObjects:#"india",#"pakistan",nil ];
}
#interface ViewController : UIViewController<kDropDownListViewDelegate>{
NSArray *arryList;
int ibtn;
}
this is my interface file
i wish to create a arraylist like arryList in the viewdidload method..i fetch the json values from restapi call and convert those into arrays...those values i get from the restapi call have to be loaded dynamically...how to do it....please suggest me ideas....
You can do it by the following way.
#interface MasterViewController ()
#property NSMutableArray *arryList;
#end
#implementation MasterViewController
#synthesize arryList;
- (void)viewDidLoad {
[super viewDidLoad];
int totalData = 10;
arryList=[[NSMutableArray alloc] initWithCapacity:totalData];
for (int i=0; i<totalData; i++) {
[arryList addObject:#""];
}
}
-(IBAction)DropDownPressed:(id)sender{
UIButton *button = (UIButton*)sender;
NSLog(#"tag:%d",button.tag);
id currentValue = [arryList objectAtIndex:button.tag];
if ([currentValue isKindOfClass:[NSString class]] && [(NSString*)currentValue isEqualToString:#""]) {
NSDictionary *dataDictionary = [[NSDictionary alloc] init];
[self getURLResponse:&dataDictionary];
NSString *myID = [dataDictionary objectForKey:#"id"];
NSString *content = [dataDictionary objectForKey:#"content"];
[arryList replaceObjectAtIndex:button.tag withObject:myID];
NSLog(#"arryList:%#",arryList);
}else{
NSLog(#"already downloaded");
}
}
-(void)getURLResponse:(NSDictionary**)dataDictionary{
NSURL *url = [NSURL URLWithString:#"http://rest-service.guides.spring.io/greeting"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:
request returningResponse:&response error:&error];
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
// ibtn=0;
// [Dropobj fadeOut];
// [self showPopUpWithTitle:#"Select Country" withOption:arryList xy:CGPointMake(16, 58) size:CGSizeMake(287, 330) isMultiple:NO];
*dataDictionary = [[NSDictionary alloc]initWithDictionary:greeting copyItems:YES];
}

How to use asynchronous data

I'm trying to fetch some data from a remote file. I'm creating an _items array inside the asynchronous request block, which is actually full of data, but when calling the _items anywhere else in my controller is still empty.
I'm not sure but i'm guessing that as the data are loaded asyncronously, when calling _items is still empty. So how how can i use the array with data, after the async task is completed?
- (IBAction)fetchEvent
{
_items = [[NSMutableArray alloc] initWithCapacity:5];
NSString *link = [NSString stringWithFormat:#"url...?id=%#", self.eId];
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *match = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray *odds = [match objectForKey:#"odds"];
OddsItem *item;
for ( NSDictionary *books in odds ) {
item = [[OddsItem alloc] init];
item.oddsBook = [odds objectForKey:#"book"];
[_items addObject:item];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchEvent];
}
mutable data is dangerous in multi thread situation. NSArray is better.
#property (nonatomic, copy) NSArray *items;
block can capture outside variables but can not modify it directly. In completion block try this
if (data.length > 0 && connectionError == nil)
{
NSDictionary *match = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSArray *odds = [match objectForKey:#"odds"];
NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:5];
for ( NSDictionary *books in odds ) {
OddsItem *item = [[OddsItem alloc] init];
item.oddsBook = [odds objectForKey:#"book"];
[items addObject:item];
}
self.items = items;
}

How we get data from server using the JSON query?

**In this code When add breakpoint from viewdidload( ) function then i got greetingArray.count zero but when i add breakpoint at the for loop then it works properly and i got the results 3 as the values of the greetingArray. What is the possible reason that no getting the data from server.There is no problem with server side.I already check for it.
- (void)viewDidLoad
{
[super viewDidLoad];
greetingArray = [[NSMutableArray alloc] init];
greetingDictionary = [[NSMutableDictionary alloc] init];
NSString *connectionString;
connectionString=[NSString stringWithFormat:#"http://xxx.xxx.x.xx/TestMgt/api/%#",self.fieldName];
NSURL *url = [NSURL URLWithString:connectionString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSLog(#"----------------------------------------------------");
NSLog(#"Data length is = %d",data.length);
greetingMArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(#"%#",greetingMArray);
for(int i = 0 ; i< greetingMArray.count; i++)
{
greetingDictionary = (NSMutableDictionary *)[greetingMArray objectAtIndex:i];
NSLog(#"%#",greetingDictionary);
ConnectionOvertime *overtime = [[ConnectionOvertime alloc] init];
overtime.entryDate=[greetingDictionary valueForKey:#"EntryDate"];
[greetingArray addObject:overtime];
NSLog(#"%d",greetingArray.count);
}
}
}];
}
if you don't get any answer try jsonFramework library and import sbjsonParser.h
for Example try below code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.ChapterID=[[NSMutableArray alloc]init];
self.ChapterName=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"https://www.coursekart.com/webservice/load-subjects.php?api_key=68410920GHJFLAC878&standard_id=2&format=json"];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url];
NSError *error;
NSURLResponse *response;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(data!=nil)
{
NSString *content=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(content.length!=0)
{
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSArray *dir=[[parser objectWithString:content]objectForKey:#"SubjectList"];
for(int i=0;i<dir.count;i++)
{
NSDictionary *array=[dir objectAtIndex:i];
NSArray *data=[array objectForKey:#"Data"];
NSDictionary *dat=(NSDictionary *)data;
NSString *idCh=[dat objectForKey:#"id"];
NSString *slug=[dat objectForKey:#"slug"];
[ChapterID addObject:idCh];
[ChapterName addObject:slug];
// NSLog(#"%#",[ChapterID objectAtIndex:0]);
//NSLog(#"%#",[ChapterName objectAtIndex:0]);
}
}
}
}

Resources