objective-c send url according to my menu select - objective-c

i have a custom UItableView . i am loading data from a API and my main view are
i am loading data from a API .
My problem is,i have a left-side menu, i want to send a url when user select any menu acoording to select menu view will load.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath{
if(indexPath.row ==0){
appdataModel.newsApiUrl = homePagesUrl;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self.revealViewController revealToggleAnimated:YES];
ContactsTableViewController *vc = [[ContactsTableViewController alloc] initWithNibName:#"ContactsTableViewController" bundle:nil];
[self.navigationController pushViewController:contView animated:YES];
}else if (indexPath.row ==1){
appdataModel.newsApiUrl = jatioNews;
NSLog(#"here 1 :%#",appdataModel.newsApiUrl);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self.revealViewController revealToggleAnimated:YES];
ContactsTableViewController *vc = [[ContactsTableViewController alloc] initWithNibName:#"ContactsTableViewController" bundle:nil];
[self.navigationController pushViewController:contView animated:YES];
}
else if (indexPath.row ==2){
appdataModel.newsApiUrl = jatioNews;
NSLog(#"here 1 :%#",appdataModel.newsApiUrl);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self.revealViewController revealToggleAnimated:YES];
ContactsTableViewController *vc = [[ContactsTableViewController alloc] initWithNibName:#"ContactsTableViewController" bundle:nil];
[self.navigationController pushViewController:contView animated:YES];
}
}
#define homePagesNews #"http://198.72.115.125/~pratidin/api/topnews"
#define jatioNews #"http://198.72.115.125/~pratidin/api/categorynews/4"
here my api link . if user select Home-menu then view will load form homePagesNews API else user select second menu then view will from jatioNews API
from this code i am getting data
-(void)GetHomePageData{
NSString *urlString = [NSString stringWithFormat:#"%#",url];
NSURL *url = [[NSURL alloc]initWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
}
now i want when user select menu may home-menu or second-menu or third-menu according to user select url link will change and view will load in my ContactsTableViewController
my ContactsTableViewController viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
appdataModel = [AppDataModel getInstance];
appdataModel.newsApiUrl = homePagesUrl;
/**** for left side menu ***/
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sideBarButton setTarget: self.revealViewController];
[self.sideBarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
/**** for Contractview***/
self.view.backgroundColor = [UIColor whiteColor];
NSString *path = [[NSBundle mainBundle] pathForResource:#"contacts" ofType:#"plist"];
contactsArray = [NSArray arrayWithContentsOfFile :path];
[self GetHomePageData];
[self.newsDataTableView reloadData];
}
some can tell me how can i solve my problem ... Thanks

Add a url property to ContactsTableViewController:
#interface ContactsTableViewController : UIViewController
#property NSURL *url;
...
#end
and in its viewDidLoad method you can load the data using whatever method you are using:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
dataTaskWithURL:self.url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Whatever
}];
Then set the URL from the tableview delegate method:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath{
if (indexPath.row ==0){
appdataModel.newsApiUrl = homePagesUrl;
} else {
appdataModel.newsApiUrl = jatioNews;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self.revealViewController revealToggleAnimated:YES];
ContactsTableViewController *vc = [[ContactsTableViewController alloc] initWithNibName:#"ContactsTableViewController" bundle:nil];
vc.url = [NSURL URLWithString:appdataModel.newsApiUrl];
[self.navigationController pushViewController:vc animated:YES];
}

Related

reloadData for TableView not loading cellForRowAtIndexPath or row count

I am trying (in vain) to reload tableView in MasterViewController from another View Controller SitesViewController. I use this code in the SitesViewController:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [[self tableView].indexPathForSelectedRow row];
//NSArray *appcell = [sitesMenu objectForKey:#"Table"];
NSLog(#"AppCell %#", sitesMenu);
NSDictionary *entry = [sitesMenu objectAtIndex:row];
self.siteid = [entry objectForKey:#"SITEID"];
NSLog(#" sample SiteView %#", siteid);
NDSClassMasterViewController *detailControllerTwo = [[NDSClassMasterViewController alloc] init];
detailControllerTwo.globalid = siteid;
NSLog(#"message %#", detailControllerTwo.globalid);
[detailControllerTwo fetchTweets];
dispatch_async(dispatch_get_main_queue(), ^{
[detailControllerTwo.tableView reloadData];
NSLog(#"%#", detailControllerTwo);
});
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
and this code for the method I am calling:
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *siteurl = [[NSString alloc] initWithFormat:#"http://adhoc.nyxtek.co.za/spfjsonws/default2.aspx?siteid=%#", globalid];
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: siteurl]];
NSError* error;
menuItems = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"%#", menuItems);
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
I have even added the reload code into the SiteViewController didSelectRow method.
I have read that I should add a property for it and synthesize but I have tried that but not sure how to add a property for UITableView to reference to the existing one.
The fetchTweets code runs, but the TableView doesn't reload.
Any assistance would be appreciated.
EDIT
This is the TableView code where I load the items in the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//NSString *name = [[[menuItems objectForKey:#"Table"] objectAtIndex:0] objectForKey:#"MENUID"];
NSDictionary *tweet = [[menuItems objectForKey:#"Table"] objectAtIndex:indexPath.row];
//NSLog(#"%#", tweet);
NSString *text = [tweet objectForKey:#"MENUDESC"];
NSString *name = [tweet objectForKey:#"MENUDESC"];
NSLog(#"TEST 1%#", text);
cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:#"by %#", name];
return cell;
}
Instead of exposing the table view via a property, why not simply write a function within the view controller that contains the code that would reload the data?
E.G. instead of:
[detailControllerTwo.tableView reloadData];
Declare a method in your MasterViewController that looks like:
- (void) updateTable
{
// tableView is declared as an IBOutlet
[tableView reloadData];
}
and then you can call that with:
dispatch_async(dispatch_get_main_queue(), ^{
[detailControllerTwo updateTable];
NSLog(#"%#", detailControllerTwo);
});

Issue with self.navigationController and pushViewController

I am having trouble pushing from a tableview to a detail view. When I click the tableview cell, the cell highlights but does not push to the detail view. I am using this to transition to the detail view:
[self.navigationController pushViewController:detailViewController animated:YES];
I have read that this is a common issue, but am somehow unable to figure out a solution. My full .m file is below. If anyone has any recommendations that would be amazing. Thank you!
#import "ViewController.h"
#import "DetailViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"title";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://website.com/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
[mainTableView reloadData];
}
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = textForMyLabel;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle: #"Back" style: UIBarButtonItemStyleBordered target: nil action: nil];
[[self navigationItem] setBackBarButtonItem: newBackButton];
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.title = [[news objectAtIndex:indexPath.row] objectForKey:#"name"];
detailViewController.newsArticle = [news objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
you try:
[self presentModalViewController: detailViewController animated:YES];
You can perform push oly with a UINavigationController, the above code will work if your Controller is UINavigationController. Since your trying to integrate two projects just check whether the RootViewController is a UINavigationController.

Issue in Using AsyncImageView in icarousel in iOS

I have developed an app which uses Asyncimageview and iCarousel.But my issues is that when i'm trying to load the images from urls only activity indicator loads in each view of my iCarousel and no images are loaded.Here is my code
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(AsyncImageView *)view
{
if (view == nil
 {
AsyncImageView * view = [[[AsyncImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 280)] autorelease];
view.image=[UIImage imageNamed:#"infobg.png"];
view.imageURL=[imageURLs objectAtIndex:index];
}
return view;
}
Follow these steps maybe because of following reasons you may face this issue
-- Check whether if ur imageURLs array is having objects under iCarousel are not...If its null you may have this kind of issue....
-- Do array allocation and add objects in
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
method,because if you add objects in your array under viewDidLoad it won't works because carousel view loads first before viewDidLoad method..
-- if your array element is present even after these steps follow this code.
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(AsyncImageView *)view
{
view = [[[AsyncImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 280)] autorelease];
view.image=[UIImage imageNamed:#"infobg.png"];
view.imageURL=[imageURLs objectAtIndex:index];
//NSLog(#"%#",imageURLs)//check imageURLs having object
if(view ==nil)
{
[[AsyncImageLoader sharedLoader]cancelLoadingImagesForTarget:view];
}
return view;
}
It will help you..
Cells should be reused
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(AsyncImageView *)view
{
if (view == nil) {
view = [[[AsyncImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 280)] autorelease];
}
// dont forget stop previous loading -cancelLoadingURL:target:
view.image=[UIImage imageNamed:#"infobg.png"];
view.imageURL=[imageURLs objectAtIndex:index];
return view;
}
also you should stop previously started
- (void)viewDidLoad
{
[super viewDidLoad];
User_Id=#"abcd#gmail.com";
NSString *Post=[NSString stringWithFormat:#"email=%#",User_Id];
NSData *PostData = [Post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *PostLengh=[NSString stringWithFormat:#"%d",[Post length]];
NSURL *Url=[NSURL URLWithString:[NSString stringWithFormat:#"%#fetch_all_user_updates.php",ServerPath]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:PostLengh forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:PostData];
NSData *ReturnData =[NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSString *Response = [[NSString alloc] initWithData:ReturnData encoding:NSUTF8StringEncoding];
Response = [Response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableArray *JSON_Array=[Response JSONValue];
// NSlog(#"%#", JSON_Array);
// textfield.text=[[JSON_Array valueforKey:#"email"]objectAtIndex:0];
// load images from database at local host
/*
NSLog(#"%#",[NSString stringWithFormat:#"%#/Images/%#",serverScriptpath,[[jsonarray valueForKey:#"image"]objectAtIndex:0]]);
NSURL *img_url=[NSURL URLWithString:[NSString stringWithFormat:#"%#/Images/%#",
serverScriptpath,[[jsonarray valueForKey:#"image"]objectAtIndex:0]]];
NSURLRequest *request1=[NSURLRequest requestWithURL:img_url];
[Img_profilepic setImageWithURLRequest:request1 placeholderImage:[UIImage imageNamed:#".png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
}];
*/
if (JSON_Array>0)
{
Array_Image_Name=[JSON_Array valueForKey:#"image_name"];
[Array_Image_Name retain];
}
else
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Failure" message:#"Error To Load Image" delegate:Nil cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[Alert show];
[Alert release];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return Array_Image_Name.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell=nil;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
AsyncImageView *Load_Image=[[AsyncImageView alloc]initWithFrame:CGRectMake(20, 10, 280, 100)];
Load_Image.imageURL=[NSURL URLWithString:[NSString stringWithFormat:#"%#/Images/%#",ServerPath,[Array_Image_Name objectAtIndex:indexPath.row]]];
Load_Image.showActivityIndicator=YES;
[cell.contentView addSubview:Load_Image];
return cell;
}
AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(0.0f, 1.0f, 320.0f, 174.0f)];
NSString *imgUrlString = photobig1;
while ([imgUrlString rangeOfString:#" "].location != NSNotFound) {
imgUrlString = [imgUrlString stringByReplacingOccurrencesOfString:#" " withString:#""];
}
UIImageView *imageview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"Loading Image.png"]];
[asyncImage addSubview:imageview];
asyncImage.tag = 999;
NSString *webStr = [NSString stringWithFormat:#"%#",imgUrlString];
NSURL *imageUrl = [[NSURL alloc] initWithString:[webStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[asyncImage loadImageFromURL:imageUrl];
[asyncImage setBackgroundColor:[UIColor clearColor]];
asyncImage.userInteractionEnabled = NO;
[scrollView addSubview:asyncImage];

web view not updating when pushed from table view

My current app consists of Navigation with Tabs, then a Table View in between, from the Table Rows when selected a Detail View is pushed. The issue I'm having is when I select a row it pushes to the Detail View and loads the html file in the Web View. However, when I navigate back and then select another row, it loads the same html from the previous selection. The only thing that stays relevant is the Title in the Navigation Title Bar.
Is this poor memory management on my part (I'm new to ObjC.. like only a week) or did I miss a step? I think me grabbing NSString *navDate = self.title; is my problem. Everything else basically works otherwise. Anyways, be gentle and thanks. :$
Table Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellID = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
if(cell == nil){
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellID];
}
cell.textLabel.font = [UIFont systemFontOfSize:15];
cell.textLabel.text = [self.dateList objectAtIndex: [indexPath row]];
return cell;
}
Row Push
(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
if(self.aTextController == nil){
ATextController *aTextDetail = [[ATextController alloc] initWithNibName:#"ArchiveData" bundle:nil];
self.aTextController = aTextDetail;
[aTextDetail release];
}
aTextController.title = [NSString stringWithFormat:#"%#", [dateList objectAtIndex:row]];
SLESDAppDelegate *delegate = (SLESDAppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate.navigationController pushViewController:aTextController animated:YES];
}
DetailView
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *navDate = self.title;
NSString *null = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", navDate] ofType:#"html"];
if(null != nil){
[webArchView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", navDate] ofType:#"html"]isDirectory:NO]]]; }
else {
[webArchView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"error" ofType:#"html"]isDirectory:NO]]];
}
}
Since you are retaining the instance of ATextController and reusing it, you will have to execute the following snippet in viewWillAppear: -
NSString *navDate = self.title;
NSString *null = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", navDate] ofType:#"html"];
if(null != nil){
[webArchView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", navDate] ofType:#"html"]isDirectory:NO]]]; }
else {
[webArchView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"error" ofType:#"html"]isDirectory:NO]]];
}
The reason being that viewDidLoad is called once when the view controller loads its view. viewWillAppear: will be called every time the view is about to come on screen.

managedObjectContext save issue

Over the last few days, I've searched far and wide and followed every resolution I could find online with no success.
Basically, I'm refreshing a Core Data entity from JSON data I pull from the web. I can clear out the previous data pulled from the web and load in the new data. The problem occurs when I attempt to save to Core Data "[self.managedObjectContext save:&error];".
The app just locks up.
The code from my view controller is shown below. I would greatly appreciate any assistance.
** CODE ***
//
// ChargeEntryViewController.m
// pcc
//
// Created by Tim Black on 3/14/11.
// Copyright 2011 Mobile Intents. All rights reserved.
//
#import "ChargeEntryViewController.h"
#import "pccAppDelegate.h"
#import "ChargeEntryPatientViewController.h"
#import "CJSONDeserializer.h"
#interface ChargeEntryViewController (PrivateMethods)
- (NSString *)jsonFromURLString:(NSString *)urlString;
- (void)handleError:(NSError *)error;
#end
#implementation ChargeEntryViewController
#synthesize fetchedResultsController=fetchedResultsController_;
#synthesize managedObjectContext=managedObjectContext_;
#synthesize providerArray;
#synthesize clearBtn;
#synthesize setBtn;
#synthesize patientController;
#pragma mark - Button methods
-(IBAction) clearAll:(id)sender{
selRow = -1;
[providerList reloadData];
}
-(IBAction) setPatientView:(id)sender {
if (self.patientController == nil) {
ChargeEntryPatientViewController *tmpController = [[ChargeEntryPatientViewController alloc] initWithNibName:#"ChargeEntryPatientView" bundle:nil];
self.patientController = tmpController;
[tmpController release];
}
patientController.title = #"Patient Selection";
[self.navigationController pushViewController:patientController animated:YES];
}
/*
Used to refresh the providers list from nrhsportal
*/
-(void)refreshProviders {
NSError *error = nil;
// get provider code from app delegate
pccAppDelegate *appDelegate = (pccAppDelegate *)[[UIApplication sharedApplication] delegate];
// first, clear out current list stored locally
NSFetchRequest *fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:#"Provider" inManagedObjectContext:self.managedObjectContext]];
NSArray *result = [self.managedObjectContext executeFetchRequest:fetch error:&error];
if (error != nil) {
[self handleError:error];
return;
}
for (id basket in result) {
[self.managedObjectContext deleteObject:basket];
}
// add (My Patients) entry
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
[newManagedObject setValue:#"(My Patients)" forKey:#"fullname"];
[self.managedObjectContext insertObject:newManagedObject];
NSString *code = appDelegate.groupCode;
// create remote source URI
NSString *urlString = [NSString stringWithFormat:#"%s%#%s", "https://nrhsportal.nrh-ok.com/pccdata.svc/GetProviders?groupcode='", code, "'&$format=json"];
NSLog(#"URL String %#", urlString);
// Perform HTTP GET to the REST web service which returns JSON
NSString *jsonString = [self jsonFromURLString:urlString];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
// Parse JSON results to convert to a dictionary
CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];
error = nil;
NSDictionary *resultsDictionary = [jsonDeserializer deserializeAsDictionary:jsonData error:&error];
if (error != nil) {
[self handleError:error];
return;
}
// Traverse through returned dictionary to populate tweets model
NSDictionary *topArray = [resultsDictionary objectForKey:#"d"];
NSArray *resultsArray = [topArray objectForKey:#"results"];
for (NSDictionary *resultDictionary in resultsArray) {
// create the
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
NSString *providerName = [resultDictionary objectForKey:#"fullname"];
[newManagedObject setValue:providerName forKey:#"fullname"];
[self.managedObjectContext insertObject:newManagedObject];
}
error = nil;
[self.managedObjectContext save:&error];
if (error != nil) {
[self handleError:error];
return;
}
[newManagedObject release];
[result release];
}
// This will issue a request to a web service API via HTTP GET to the URL specified by urlString.
// It will return the JSON string returned from the HTTP GET.
- (NSString *)jsonFromURLString:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[request release];
[self handleError:error];
NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
return [resultString autorelease];
}
// This shows the error to the user in an alert.
- (void)handleError:(NSError *)error {
if (error != nil) {
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil];
[errorAlertView show];
[errorAlertView release];
}
}
#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
selRow = -1;
// refresh the provider list from remote data
[self refreshProviders];
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[managedObject valueForKey:#"fullname"] description];
cell.textLabel.font=[UIFont systemFontOfSize:16.0];
if ([cell.textLabel.text isEqualToString: #"(My Patients)"]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// Reflect selection in data model
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
// Reflect deselection in data model
}
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController_ != nil) {
return fetchedResultsController_;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"fullname" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController_;
}
#pragma mark - Memory management
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[patientController release];
[clearBtn release];
[setBtn release];
[providerArray release];
[fetchedResultsController_ release];
[managedObjectContext_ release];
[super dealloc];
}
#end
You don't need the line
[self.managedObjectContext insertObject:newManagedObject];
since you've already insertNewObjectForEntityForName before with the newManagedObject.