I got the following problem: The labels always change to the ones definied in tag 9001. Could someone help me spot my error?
ViewController.m:
- (IBAction)switch0:(id)sender
{(button.tag = 9001);
UIButton *buttonPressed = (UIButton *)sender;
SecondViewController *second =[[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
second.buttonTag = buttonPressed.tag;
}
- (IBAction)switch2:(id)sender2
{ (button2.tag = 9002);
UIButton *buttonPressed = (UIButton *)sender2;
SecondViewController *third =[[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:third animated:YES];
second.buttonTag = buttonPressed.tag;
}
SecondViewcontroller.m
- (void)viewDidLoad
{
[super viewDidLoad];
if (buttonTag == 9001) {
self.label1.text = [[NSString alloc] initWithFormat:#"Radnomtext"];
self.label2.text = [[NSString alloc] initWithFormat:#"Randomtext"];
self.label3.text = [[NSString alloc] initWithFormat:#"Randomtext?"];
}
if (buttonTag == 9002) {
self.label1.text = [[NSString alloc] initWithFormat:#"Radnomtext2"];
self.label2.text = [[NSString alloc] initWithFormat:#"Randomtext2"];
self.label3.text = [[NSString alloc] initWithFormat:#"Randomtext2?"];
Heres an example and your presenting the view twice I took out the modal in this example:
- (IBAction)switch0:(id)sender
{
UIButton *buttonPressed = (UIButton *)sender;
SecondViewController *second =[[SecondViewController alloc] initWithNibName:nil bundle:nil];
NSInteger tagToSet = 9001;
second.buttonTag = tagToSet;;
[self.navigationController pushViewController:second animated:YES];
}
and using the keyword switch is no good. It is a reserved word in Objective C.
Maybe because you forgot to close the ending bracket for first if?
if (buttonTag == 9001) {
self.label1.text = [[NSString alloc] initWithFormat:#"Radnomtext"];
self.label2.text = [[NSString alloc] initWithFormat:#"Randomtext"];
self.label3.text = [[NSString alloc] initWithFormat:#"Randomtext?"];
} // bracket supposed to be here
if (buttonTag == 9002) {
or maybe you set buttonTag to incorrect instance?
- (IBAction)switch2:(id)sender2
{
UIButton *buttonPressed = (UIButton *)sender2;
SecondViewController *third =[[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:third animated:YES];
second.buttonTag = buttonPressed.tag; // supposed to be third?
[self.navigationController pushViewController:third animated:YES];
(button2.tag = 9002);
}
And to be safe, you should set buttonTag before presentModalViewController.
Related
In my app when I visit certain view controllers and touch the Back button in the navigation bar, the navigation title of the resulting viewcontroller looks to be coming from the upper left corner and it looks ugly.
A picture of such an instance is shown below.
I have set the titles programatically.
Can somebody please tell me why this is happening and how I could fix it? Thanks in advance.
Here is my code:
ViewController B
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,120,45)] ;
label.textColor = COLOR_TEXT_NAVIGATION_BAR_COLOR;
label.backgroundColor = [UIColor clearColor];
label.font = FONT_NAVIGATION_TITLE_BAR;
label.text = [NSString stringWithFormat:PAGE_TITLE_ADD_SERVICE_PROVIDER];
self.navigationItem.titleView = label;
[label sizeToFit];
UIButton *homeButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 20, 20)];
[homeButton setImage:[UIImage imageNamed:IMG_HOME_MENU_BUTTON] forState:UIControlStateNormal];
[homeButton addTarget:self action:#selector(homeMenuAction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:homeButton];
accNumTextFiled.delegate=self;
nameTextFiled.text = addPayee.providerName;
payLimitTextFiled.text = [NSString stringWithFormat:#"%9.2f", addPayee.paymentLimit];//[NSString stringWithFormat:#"%f",addPayee.paymentLimit];
descTextFiled.text = addPayee.description;
catTextFiled.text = addPayee.maincategory;
subCatTextFiled.text = addPayee.subcategory;
accNumTextFiled.text = addPayee.paymentAccountNumber;
[accNumTextFiled setKeyboardType:UIKeyboardTypeNumberPad];
[self labelCss];
scrollView.contentSize=CGSizeMake(320,450);
}
ViewController A
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = COLOR_BG_INNER_PAGE_COLOR;
NSArray *mappingObjArray1 = #[#"providerName",#"description",#"paymentLimit",#"providerCode",#"maincategory",#"subcategory"];
NSDictionary *queryParams = #{};
commonRestDataMapping = nil;
commonRestDataMapping = [[CommonRestDataMapping alloc] init];
commonRestDataMapping.restDataMappingDelegate = self;
commonRestDataMapping.servicePath = REST_WEB_SERVICE_ADD_PAYEE_LIST;
commonRestDataMapping.mappingObjArray = mappingObjArray1;
commonRestDataMapping.mappingClassString = #"AddPayee";
commonRestDataMapping.mappingKeyPath = #"data";
commonRestDataMapping.mappingQueryParams = queryParams;
[commonRestDataMapping configureRestKit];
[commonRestDataMapping loadDataArray];
if ([self respondsToSelector:#selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone;
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[super createNavigationBar:USER_ACCOUNT_PAGE];
[super setNavihationTitle:PAGE_TITLE_ADD_PAYEE];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//WEB service data initilization
[[WebServiceUrl getSharedInstance] dataiInitialize];
[GMSServices provideAPIKey:#"AIzaSyCBfhnMtcmdhJaaqff72PlvJIjBTZpfSu4"];
NSString* docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString* dbPath = [docPath stringByAppendingPathComponent:#"datadb.sqlite"];
NSFileManager *fm = [NSFileManager defaultManager];
// Check if the database is existed.
if(![fm fileExistsAtPath:dbPath])
{
// If database is not existed, copy from the database template in the bundle
NSString* dbTemplatePath = [[NSBundle mainBundle] pathForResource:#"datadb" ofType:#"sqlite"];
NSError* error = nil;
[fm copyItemAtPath:dbTemplatePath toPath:dbPath error:&error];
if(error){
NSLog(#"can't copy db.");
} else{
NSLog(#" copy db.");
}
} else {
NSLog(#" db exsists");
}
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
UIView *addStatusBar = [[UIView alloc] init];
addStatusBar.frame = CGRectMake(0, 0, 1024, 20);
addStatusBar.backgroundColor = [UIColor blackColor]; //change this to match your navigation bar
[self.window.rootViewController.view addSubview:addStatusBar];
}
homeViewController = [[HomeViewController alloc] initWithNibName:#"HomeViewController" bundle:nil];
UINavigationController *myNav1=[[UINavigationController alloc] initWithRootViewController:homeViewController];
UIImage *navBackgroundImg = [UIImage imageNamed:#"aa1.png"];
[myNav1.navigationBar setBackgroundImage:navBackgroundImg forBarMetrics:UIBarMetricsDefault];//iOS 5 only
// Override point for customization after application launch.
self.viewController = myNav1;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)transitionToViewController:(UIViewController *)viewController
withTransition:(UIViewAnimationOptions)transition
{
[UIView transitionFromView:self.window.rootViewController.view
toView:viewController.view
duration:0.35f
options:transition
completion:^(BOOL finished){
self.window.rootViewController = viewController;
}];
}
First off: My project is ARC enabled and I'm using storyboard.
I have a view controller that pushes a segue (modal),
[self performSegueWithIdentifier: #"goInitialSettings" sender: self];
there i'm setting some parameters and store them. When the parameters are stored (true a button tap), the app should return to the original viewcontroller.
This i am doing with this command:
[self.presentingViewController dismissViewControllerAnimated:NO completion:^{}];
I'm noticing that the viewcontroller that i dismiss, never deallocs. How does this come?
I'm adding the code of the 'presented viewcontroller' below:
#interface CenterChoiceController ()
{
UIView* _titleBackground;
UILabel* _lblTitle;
UIButton* _btnGaVerder;
UIPickerView* _myPickerView;
NSArray* _centers;
UILabel* _adresLine;
UILabel* _cityLine;
MKPointAnnotation* _point;
MKMapView* _mapView;
UIActivityIndicatorView* _indicator;
UIAlertView* _alert;
GCenter* _center;
DataManager* _dm;
}
#end
#implementation CenterChoiceController
-(void)dealloc
{
NSLog(#"Centerchoice deallocs");
_titleBackground = nil;
_lblTitle = nil;
_btnGaVerder = nil;
_myPickerView = nil;
_point = nil;
_mapView = nil;
_indicator = nil;
_alert = nil;
_centers = nil;
_adresLine = nil;
_cityLine = nil;
_center = nil;
_dm = nil;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_dm = [[DataManager alloc]init];
if([_dm hasConnectivity])
{
[_dm fetchCentersForController:self];
}
else
{
[self pushErrorMessage:NSLocalizedString(#"nointernetconnection", nil)];
}
CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];
_titleBackground = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
_titleBackground.backgroundColor = [GColor blueColor];
[self.view addSubview:_titleBackground];
_lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 10, 44)];
_lblTitle.textAlignment = NSTextAlignmentRight;
_lblTitle.textColor = [GColor whiteColor];
_lblTitle.text = NSLocalizedString(#"bioscoopkeuze", nil);
[self.view addSubview:_lblTitle];
_btnGaVerder = [[UIButton alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 54, self.view.frame.size.width, 54)];
[_btnGaVerder setTitle:NSLocalizedString(#"gaverder", nil) forState:UIControlStateNormal];
_btnGaVerder.titleLabel.font = [_btnGaVerder.titleLabel.font fontWithSize:12];
_btnGaVerder.backgroundColor = [GColor blueColor];
[_btnGaVerder setTitleColor:[GColor whiteColor] forState:UIControlStateNormal];
[_btnGaVerder setShowsTouchWhenHighlighted:YES];
[_btnGaVerder addTarget:self action:#selector(gaVerder) forControlEvents:UIControlEventTouchUpInside];
_myPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 200)];
}
-(void)showLoading
{
NSLog(#"shows loading");
_indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint cntr = self.view.center;
_indicator.center = cntr;
[_indicator startAnimating];
[self.view addSubview:_indicator];
}
-(void)hideLoading
{
NSLog(#"hides loading");
[_indicator removeFromSuperview];
_indicator = nil;
}
-(void)pushData:(NSArray *)data
{
[self.view addSubview:_btnGaVerder];
[self.view addSubview:_myPickerView];
_centers = data;
_myPickerView.delegate = self;
_myPickerView.dataSource = self;
_dm = [[DataManager alloc]init];
GSettings* settings = [_dm loadSettings];
if(settings == nil)
{
settings = [[GSettings alloc]init];
settings.chosenCenter = [_centers objectAtIndex:0];
settings.loadedCenter = [_centers objectAtIndex:0];
_center = settings.chosenCenter;
settings.notificationsEnabled = YES;
[self changeAddressLines];
}
/*if(settings != nil)
{
GCenter* loaded = settings.loadedCenter;
int i = 0;
BOOL found = NO;
while(i < [_centers count] && !found)
{
GCenter* center = (GCenter*)[_centers objectAtIndex:i];
if(settings.loadedCenter.iD == center.iD)
{
_center = center;
settings.chosenCenter = center;
[_dm storeSettings:settings];
found = YES;
}
i++;
}
//[self.myPickerView selectRow:i-1 inComponent:0 animated:NO];
loaded = nil;
[self changeAddressLines];
}
*/
}
-(void) pushErrorMessage: (NSString*) errorMessage
{
_alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"fout", nil) message:errorMessage delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
_alert.delegate = self;
[_alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)
{
if(self.navigationController != nil)
{
[self.navigationController popViewControllerAnimated:YES];
}
else
{
//[self initializeData];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated
{
[_dm cancelCenterRequest];
/*if(self.tabBarController != nil)
{
dm = [[DataManager alloc]init];
settings = [dm loadSettings];
if([dm hasConnectivity])
{
settings.lastUpdated = nil;
[dm storeSettings:settings];
}
if(settings.loadedCenter.centerCode != settings.chosenCenter.centerCode)
{
UIStoryboard *mystoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SplashScreenController *controller = [mystoryboard instantiateViewControllerWithIdentifier:#"root"];
[self presentViewController:controller animated:YES completion:nil];
}
dm = nil;
settings = nil;
}
*/
}
-(void)gaVerder
{
_dm = [[DataManager alloc]init];
GSettings* settings = [_dm loadSettings];
if(settings == nil)
{
settings = [[GSettings alloc]init];
settings.notificationsEnabled = YES;
}
if(_center != nil)
{
settings.chosenCenter = _center;
}
[_dm storeSettings:settings];
[_mapView removeFromSuperview];
_mapView = nil;
_titleBackground = nil;
_lblTitle = nil;
_btnGaVerder = nil;
_myPickerView = nil;
_point = nil;
_indicator = nil;
_alert = nil;
_centers = nil;
_adresLine = nil;
_cityLine = nil;
_center = nil;
_dm = nil;
[self.presentingViewController dismissViewControllerAnimated:NO completion:^{}];
//DEZE BLIJFT HELAAS IN HET GEHEUGEN HANGEN... GEEN OPLOSSING GEVONDEN
//[self.navigationController popViewControllerAnimated:NO];
}
//PICKERVIEWDELEGATE EN DATASOURCE
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [_centers count];
}
- (UILabel *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
GCenter* center = (GCenter*)[_centers objectAtIndex:row];
NSString* string = center.name;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
label.textColor = [GColor blueColor];
label.font = [label.font fontWithSize:18];
label.text = string;
label.textAlignment = NSTextAlignmentCenter;
return label;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
_center = (GCenter*)[_centers objectAtIndex:row];
[self changeAddressLines];
}
-(void)changeAddressLines
{
if (_mapView != nil)
{
[_mapView removeAnnotation:_point];
}
[_adresLine removeFromSuperview];
[_cityLine removeFromSuperview];
_adresLine = nil;
_cityLine = nil;
CGRect rctAdres = CGRectMake(0, _myPickerView.frame.origin.y + _myPickerView.frame.size.height -10, self.view.frame.size.width, 20);
_adresLine = [[UILabel alloc]initWithFrame:rctAdres];
_adresLine.textAlignment = NSTextAlignmentCenter;
_adresLine.textColor = [GColor greyColor];
_adresLine.text = _center.street;
CGRect rctCity = CGRectMake(0, rctAdres.origin.y + rctAdres.size.height, self.view.frame.size.width, 20);
_cityLine = [[UILabel alloc]initWithFrame:rctCity];
_cityLine.textAlignment = NSTextAlignmentCenter;
_cityLine.textColor = [GColor greyColor];
_cityLine.font = [_cityLine.font fontWithSize:14];
_cityLine.text = _center.city;
[self.view addSubview:_adresLine];
[self.view addSubview:_cityLine];
if(_mapView == nil)
{
double height;
height = _btnGaVerder.frame.origin.y - _cityLine.frame.origin.y - _cityLine.frame.size.height;
CGRect mapRect = CGRectMake(0, _cityLine.frame.origin.y+3 + _cityLine.frame.size.height, self.view.frame.size.width, height);
_mapView = [[MKMapView alloc]initWithFrame:mapRect];
[self.view addSubview:_mapView];
}
CLLocationCoordinate2D punt;
punt.latitude = _center.latitude;
punt.longitude = _center.longitude;
_point = [[MKPointAnnotation alloc] init];
[_point setCoordinate:punt];
_mapView.centerCoordinate = punt;
_point.title = _center.name;
[_mapView addAnnotation:_point];
[_mapView setCenterCoordinate:punt animated:YES];
MKCoordinateRegion theRegion = _mapView.region;
theRegion.span.longitudeDelta = 0.005;
theRegion.span.latitudeDelta = 0.005;
[_mapView setRegion:theRegion animated:YES];
}
#end
In my case it was a little more complicated. I don't have any variable that has strong reference to my view controller, and my view controller is not a strong delegate to any property/variable contained inside this class itself. After some hard thinking and trials, I found my issue was caused by a NSTimer object defined in the interface. The timer object itself is non-repeatable, but the method invoked by it will schedule the timer again at the end, which as you can imagine would reference this method defined in my view controller again, thus causing circular references. To break out of this loop, I had to invalidate the timer before I dismiss my view controller.
As a summary, these are cases when a view controller can be blocked from deallocating after it is dismissed:
The view controller is being strongly referenced by some outside object;
The view controller is a strong delegate referenced by some object defined within the view controller itself
The dismissViewControllerAnimated:completion: block may reference to self or it has some other code block that may cause a circular references
The view controller has NSTimer objects which can invoke some methods which re-schedules the timer
There could be more, but hopefully we can capture a lot of cases with the above cases.
If your view controller is not deallocated after it is dismissed, there's probably a strong reference to that view controller somewhere in your code. ARC will always deallocate objects that doesn't have strong reference anymore.
I'm trying to implement a basic QuickDialog view and the placement of the elements works fine.
But when I select an element the view won't scroll it into view. I thought the library would do this by itself or am I missing something?
Here is my code:
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
QRootElement *root = [[QRootElement alloc] init];
root.title = #"";
root.grouped = YES;
self.root = root;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
QSection *driverSection = [[QSection alloc] initWithTitle:#"xxx"];
QEntryElement *lblDriverSsn = [[QEntryElement alloc] initWithTitle:#"xxx" Value:#""];
lblDriverSsn.key = #"driverSsn";
QSection *vehicleSection = [[QSection alloc] initWithTitle:#"xxx"];
NSArray *component1 = #[#"xxx", #"xxx"];
QPickerElement *EventDescriptionPicker = [[QPickerElement alloc] initWithTitle:#"xxx" items:#[component1] value:#""];
EventDescriptionPicker.key = #"eventDescription";
NSMutableArray *speedValues = [[NSMutableArray alloc]init];
for (int i = 0; i <= 201; i+=5)
{
[speedValues addObject:[NSString stringWithFormat:#"%d%#", i,#" km/h"]];
}
QPickerElement *vehicleSpeed = [[QPickerElement alloc] initWithTitle:#"xxx" items:#[speedValues] value:#""];
self.damageReported = [[QBooleanElement alloc] initWithTitle:#"xxx" BoolValue:NO];
self.damageReported.onImage = [UIImage imageNamed:#"imgOn"];
self.damageReported.offImage = [UIImage imageNamed:#"imgOff"];
self.damageReported.controllerAction = #"showReportNumber:";
QEntryElement *lblReportNumber = [[QEntryElement alloc] initWithTitle:#"xxx" Value:#""];
lblDriverSsn.key = #"reportNumber";
//Sections
[driverSection addElement:lblDriverSsn];
[self.root addSection:driverSection];
[vehicleSection addElement:EventDescriptionPicker];
[vehicleSection addElement:vehicleSpeed];
[vehicleSection addElement:self.damageReported];
[vehicleSection addElement:lblReportNumber];
[self.root addSection:vehicleSection];
}
Am I missing something here?
Thanks in advance
On your initWithCoder: , set the following:
self.resizeWhenKeyboardPresented =YES;
This causes the view controller to listen for keyboard notifications , and adjust the inset accordingly.
What I m Thinking to do is ? there is one MainViewController in which there are two UIViews one loaded UITableViewController and other UIPageViewController.
In TableViewController, there are list of pdf's names. But when i click of the pdf list, it does not loads the PageViewController with new pdf in context.
Pdf file names are store in .plist file, Pdfs are fetch from NSBundle or NSDocumentDirectory
In TableViewController
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Play *play = (Play *)[[self.sectionInfoArray objectAtIndex:indexPath.section] play];
Quotation *qute = [play.Details objectAtIndex:indexPath.row];
if ([qute.Key isEqualToString:#"ABC"])
{
AppDelegate *app = [[UIApplication sharedApplication]delegate];
app.strpdfname = qute.Value;
MiddleViewController *mid = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
ContentViewController *cvc = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
[mid viewDidLoad];
[cvc viewDidLoad];
}
else
{
MainViewController *vc = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
[vc viewDidLoad];
}
}
In PageViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.modelArray = [[NSMutableArray alloc] init];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
NSURL *targetURL = [NSURL fileURLWithPath:path];
originalPDF = CGPDFDocumentCreateWithURL((__bridge CFURLRef)targetURL);
numberOfPages = CGPDFDocumentGetNumberOfPages(originalPDF);
for (int index = 0; index < numberOfPages ; index++)
{
[self.modelArray addObject:[NSString stringWithFormat:#"%d",index]];
}
self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageViewController.delegate = self;
self.pageViewController.dataSource = self;
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
contentViewController.labelContents = [self.modelArray objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];
CGRect pageViewRect = self.view.frame;
pageViewRect = CGRectInset(pageViewRect, 0.0, 0.0);
self.pageViewController.view.frame = pageViewRect;
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerBeforeViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == 0)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex - 1];
return contentViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerAfterViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == self.modelArray.count-1)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex + 1];
return contentViewController;
}
- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];
self.pageViewController.doubleSided = NO;
return UIPageViewControllerSpineLocationMin;
}
In ContentViewController of PageViewController
-(UIImage*) imageFromPDF:(CGPDFDocumentRef)pdf withPageNumber:(NSUInteger)pageNumber withScale:(CGFloat)scale
{
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf,pageNumber);
CGRect tmpRect = CGPDFPageGetBoxRect(pdfPage,kCGPDFMediaBox);
CGRect rect = CGRectMake(tmpRect.origin.x,tmpRect.origin.y,tmpRect.size.width*scale,tmpRect.size.height*scale);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context,-50,rect.size.height-30);
CGContextScaleCTM(context,scale,-scale);
CGContextDrawPDFPage(context,pdfPage);
UIImage* pdfImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return pdfImage;
}
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
i = [labelContents intValue];
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
if (i!=0)
{
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path]);
UIImage *img = [[UIImage alloc] init];
img = [self imageFromPDF:pdf withPageNumber:i withScale:1];
UIImageView *imgview1 = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgview1];
}
else
{
UIImage *imgmain = [UIImage imageNamed:#"Diary4.png"];
UIImageView *imgvmain = [[UIImageView alloc] initWithImage:imgmain];
imgvmain.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y,580,self.view.frame.size.height);
[self.view addSubview:imgvmain];
}
}
In MainViewController
-(void)viewDidload
{
leftView = [[UIView alloc] initWithFrame:CGRectMake(5,25, 200,715)];
leftView.backgroundColor = [UIColor clearColor];
tvc = [[TableViewController alloc] initWithStyle:UITableViewStylePlain];
tvc.plays = self.plays;
tvc.view.frame = leftView.frame;
leftView.clipsToBounds = YES;
[leftView addSubview:tvc.view];
[self.view addSubview:leftView];
middleView = [[UIView alloc] initWithFrame:CGRectMake(107, 30, 575, 670)];
mvc = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
[mvc.view setFrame:middleView.frame];
[middleView addSubview:mvc.view];
[self.view addSubview:middleView];
}
As there is no reload data method for UIPageViewController. I was using UIPageViewController in UIViewController instead of that I use UINavigationController in which the UIPageViewController can be reloaded with dynamic data.So on click of UITableViewController, data is sends to UINavigationController-->UIPageViewController. This has solved the above issue.
When my view is trying to load, the applications crashes and i get this stack:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
This is my code, i don't really know where to look when this crash is occurred:
#import "Itineraire.h"
#import "SBMapView.h"
#import "SBRouteAnnotation.h"
#import "City.h"
#import "UICGRoutes.h"
#import "SBCheckPointViewController.h"
//#import "SBRouteDetailView.h"
#interface Itineraire(Private)
-(void)customInitialization;
#end
#implementation Itineraire(Private)
-(void)customInitialization
{
// do the initialization of class variables here..
mDirections = [UICGDirections sharedDirections];
mDirections.delegate = self;
}
#end
#implementation Itineraire
#synthesize map = mMap;
#synthesize startPoint = mStartPoint;
#synthesize endPoint = mEndPoint;
#synthesize loadBtn = mLoadBtn;
#synthesize annotationArray = mAnnotationArray;
#synthesize travelMode = mTravelMode;
#synthesize destination;
#synthesize routes;
#synthesize mAnnotations;
#synthesize mRouteArray;
#synthesize mRouteDetail;
//Invoked when the class is instantiated in XIB
-(id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if( self)
{
[self customInitialization];
}
return self;
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
[self customInitialization];
}
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Google Maps";
self.map = [[SBMapView alloc] initWithFrame:CGRectMake(0, 49, self.view.frame.size.width, self.view.frame.size.height)];
//self.map = [[SBMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 381)];
[self.view addSubview:mMap];
self.view.backgroundColor = [UIColor blackColor];
self.annotationArray = [[NSMutableArray alloc]init];
self.routes = [[UICGRoutes alloc]init];
if (mDirections.isInitialized) {
[self updateRoute];
}
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
}
- (void)viewWillDisappear:(BOOL)animated;
{
[super viewWillDisappear:YES];
}
#pragma mark -
#pragma mark Instance Methods
- (void)updateRoute
{ /*
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
UICGDirectionsOptions *options = [[[UICGDirectionsOptions alloc] init] autorelease];
options.travelMode = mTravelMode;
City *mFirstCity = [[[City alloc]init] autorelease];
mFirstCity.mCityName = #"Paris";//mStartPoint;
//[mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:destination options:options];
//added
NSMutableArray * DestinationCityArray = [[NSMutableArray alloc]init];
[DestinationCityArray addObject:#"Berlin"];
[mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:destination options:options];
*/
//
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
UICGDirectionsOptions *options = [[UICGDirectionsOptions alloc] init] ;
options.travelMode = mTravelMode;
City *mFirstCity = [[City alloc]init];
mFirstCity.mCityName = #"Amsterdam";//mStartPoint;
NSMutableArray *dest=[[NSMutableArray alloc]init];
[dest addObject:#"Berlin"];
[mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:dest options:options];
}
-(void)loadRouteAnnotations
{
self.mRouteArray = [mDirections routeArray];
NSLog(#"mRouteArray %#",mRouteArray);
self.mAnnotations = [[NSMutableArray alloc]init];
for (int idx = 0; idx < [mRouteArray count]; idx++) {
NSArray *_routeWayPoints1 = [[mRouteArray objectAtIndex:idx] wayPoints];
NSArray *mPlacetitles = [[mRouteArray objectAtIndex:idx] mPlaceTitle];
self.annotationArray = [NSMutableArray arrayWithCapacity:[_routeWayPoints1 count]-2];
mLoadBtn.title = #"OFF";
mLoadBtn.target = self;
mLoadBtn.action = #selector(removeRouteAnnotations);
for(int idx = 0; idx < [_routeWayPoints1 count]-1; idx++)
{
mBetweenAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[_routeWayPoints1 objectAtIndex:idx]coordinate]
title:[mPlacetitles objectAtIndex:idx]
annotationType:SBRouteAnnotationTypeWayPoint];
[self.annotationArray addObject:mBetweenAnnotation];
}
[mAnnotations addObject:mAnnotationArray];
[self.map.mapView addAnnotations:[mAnnotations objectAtIndex:idx]];
NSLog(#"map %#",mMap);
}
}
-(void)showCheckpoints
{
SBCheckPointViewController *_Controller = [[SBCheckPointViewController alloc]initWithNibName:#"SBCheckPoints" bundle:nil];
[self.navigationController pushViewController:_Controller animated:YES];
NSMutableArray *arr = [[mDirections checkPoint] mPlaceTitle];
_Controller.mCheckPoints = arr ;
}
//
-(void)removeRouteAnnotations
{
NSMutableArray *mTempAnnotation;// = [mAnnotations retain];
for (int idx = 0; idx < [mTempAnnotation count]; idx++) {
[mMap.mapView removeAnnotations:[mTempAnnotation objectAtIndex:idx] ];
}
mLoadBtn.title = #"ON";
mLoadBtn.target = self;
mLoadBtn.action = #selector(loadRouteAnnotations);
}
#pragma mark <UICGDirectionsDelegate> Methods
- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
[self updateRoute];
}
- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
- (void)directionsDidUpdateDirections:(UICGDirections *)indirections {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UICGPolyline *polyline = [indirections polyline];
NSArray *routePoints = [polyline routePoints];
[mMap loadRoutes:routePoints]; // Loads route by getting the array of all coordinates in the route.
UIToolbar *tools = [[UIToolbar alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
tools.clearsContextBeforeDrawing = NO;
tools.clipsToBounds = NO;
tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.
// anyone know how to get it perfect?
tools.barStyle = -1; // clear background
NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:2];
// Create a standard Load button.
self.loadBtn = [[UIBarButtonItem alloc]initWithTitle:#"ON"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(loadRouteAnnotations)];
[buttons addObject:mLoadBtn];
// Add Go button.
UIBarButtonItem *mGoBtn = [[UIBarButtonItem alloc] initWithTitle:#"Go"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(showCheckpoints)];
[buttons addObject:mGoBtn];
// Add buttons to toolbar and toolbar to nav bar.
[tools setItems:buttons animated:NO];
UIBarButtonItem *twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = twoButtons;
//Add annotations of different colors based on initial and final places.
SBRouteAnnotation *startAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
title:mStartPoint
annotationType:SBRouteAnnotationTypeStart];
SBRouteAnnotation *endAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
title:mEndPoint
annotationType:SBRouteAnnotationTypeEnd];
[mMap.mapView addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation,nil]];
}
- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
#pragma mark -
#end
I tried to put my code on a new project (empty application) and it worked fine, i didn't understand that error and its possible causes.
EDIT:
I tried to track the problem by elimination,and my code worked fine when i remove this method:
//Invoked when the class is instantiated in XIB
-(id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if( self)
{
[self customInitialization];
}
return self;
}
However, when i run, my app doesn't display me the route between the two points (The purpose of the app). So this method seems important for the whole class because without it, i couldn't get the route and in the other side when it's there, the app crashes. How should i deal with this contradiction?
#Vince is putting you on the right track. Since the problem is in an NSURL method being called by a framework (Google Maps in this case) you need to debug what you are passing to the framework. You have the source for the framework also right? You can set breakpoints in loadWithStartPoint:endPoint:options:] to see what's going on.
One thing I did notice is you are passing an NSMutableArray as the endPoint param when I believe it expects an NSString.