**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]);
}
}
}
}
Related
I'm new to Objective-C, just wondering how to use NSArray object outside from JSON.
For example:
NSURL *url = [NSURL URLWithString:#"http://acumen-locdef.elasticbeanstalk.com/service/countries"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSMutableArray *myFinalListArray = [[NSMutableArray alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSMutableArray *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
for (NSDictionary *countryList in greeting) {
[myFinalListArray addObject:countryList[#"name"]];
}
}
NSLog(#"%#",myFinalListArray); //(This one showing all results..)
}];
NSLog(#"%#",myFinalListArray); //(This one giving empty result)
I have defined myFinalListArray and added objects in for loop.
If you use NSLog inside the loop or outside the loop it will show you results. But if I use this after }]; (after the code is ending.),
it's giving me empty array.
If you are accessing myFinalListArray in tableview then you can reload tableview inside the block after fetching data.
Or if you are accessing this array in some other task then you have to make notification call (have to add observer) and then post notification that will call some other method and access your array there and do your further stuff.
The block of code associated with sendAsynchronousRequest isn't executed until the network fetch has completed; this takes some time. While the network fetch is happening your code continues to execute, starting with the line immediately after sendAsynchronousRequest which is NSLog(#"%#",myFinalListArray); - but because the network operation hasn't completed you get an empty array.
In the block you need to include the code that you need to process the array, update your user interface or whatever (If you update UI make sure you dispatch the operation on the main thread)
This will work. You can try with this.
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *myFinalListArray = [[NSMutableArray alloc] init];
//Pass here the reference the a array. It will return you the array of you county when downloaded complete.
[self getURLResponse:&myFinalListArray];
NSLog(#"countryArray:%#",myFinalListArray);
}
-(void)getURLResponse:(NSMutableArray**)countryArray{
NSURL *url = [NSURL URLWithString:#"http://acumen-locdef.elasticbeanstalk.com/service/countries"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSMutableArray *myFinalListArray = [[NSMutableArray alloc] init];
NSURLResponse *response;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:
request returningResponse:&response error:&error];
NSMutableArray *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
for (NSDictionary *countryList in greeting) {
[myFinalListArray addObject:countryList[#"name"]];
}
*countryArray = [[NSMutableArray alloc]initWithArray:myFinalListArray copyItems:YES];
}
-(void)sendRequest
{
NSURL *url = [NSURL URLWithString:#"http://acumen-locdef.elasticbeanstalk.com/service/countries"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSMutableArray *myFinalListArray = [[NSMutableArray alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
if (data.length > 0 && connectionError == nil)
{
NSMutableArray *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if( !myFinalListArray )
{
myFinalListArray=[[NSMutableArray alloc]init];
}
for (NSDictionary *countryList in greeting) {
[myFinalListArray addObject:countryList[#"name"]];
}
}
[self printArray];
}];
}
//create method that will execute after response
-(void) printArray
{
NSLog(#"%#",myFinalListArray); //(This one showing all results..)
}
Use
__block NSMutableArray *myFinalListArray = [[NSMutableArray alloc] init];
This should work.
Happy Coding.
sendAsynchronousRequest runs asynchronously, meaning that the code below is already performed while the request is still running, so the NSLog is logging the empty array.
Only when the request finishes, the array is filled up but your outer NSLog was already performed.
-(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];
}
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.
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 can i display image into UICollectionView using Cache and display large image into another
View on UICollectionView didSelect. Here both large and thumb image on CollectionView so next view large image not blank.using EMAsyncImageView
NSURL *url = [NSURL URLWithString:#"http://leewayinfotech.com/mobile/girlwallpaper/api.php?category=abstract&device=i5&hits=all"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"Response String=%#",responseString);
NSError *jsonError;
NSData *trimmedData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:trimmedData options:NSJSONReadingAllowFragments error:&jsonError];
if (jsonError) {
NSLog(#"JSON parse error: %#", jsonError);
return;
}
obj_Array=[[NSMutableArray alloc] init];
obj_Array=[json objectForKey:#"wallpaper"];
//NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.thumb_img_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.device_img_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.imgNo_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
for (int i=0; i<[obj_Array count]; i++) {
ImgClass *obj_Class=[[ImgClass alloc] init];
obj_Class.main_id=[[[obj_Array objectAtIndex:i] valueForKey:#"id"] integerValue];
[obj_Class.thumb_img_Array addObject:[[[obj_Array objectAtIndex:i] objectForKey:#"images"] objectForKey:#"image_thumb"]];
[obj_Class.device_img_Array addObject:[[[obj_Array objectAtIndex:i] objectForKey:#"images"] objectForKey:#"image2"]];
NSLog(#"Thumb-->%#\n\nDevice-->%#",[obj_Class.thumb_img_Array description],[obj_Class.device_img_Array description]);
[appDelg.my_Array addObject:obj_Class];
}
you use the EGOImageView for image caching support.
You can use SDWebImage.Using SDWebImage you can set image using imageURLString like below with CacheType.
[yourImgView setImageWithURL:[NSURL URLWithString:imageURLString]
placeholderImage:[UIImage imageNamed:#"noimage.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
if (!error && image)
{
}
}];
Hope it will helps you..