I'm having problems getting the current URL through a URL request and passing it on to the text field above my web view. I tried logging it and it returns NULL, and the text field remains blank.
This is the delegate I added to my implementation file:
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSURL* url = [webView.request URL];
_webAddress.text = [url absoluteString];
}
And here is my WebViewController.h file:
#import <UIKit/UIKit.h>
#interface WebViewController : UIViewController {
IBOutlet UIWebView *_webView;
IBOutlet UITextField *_webAddress;
IBOutlet UIActivityIndicatorView *activityIndicator;
NSTimer *timer;
NSString *_webURL;
}
#property (nonatomic, retain) IBOutlet UIWebView *webView;
#property (nonatomic, retain) IBOutlet UITextField *webAddress;
#property (nonatomic, retain) NSString *webURL;
- (IBAction) doneButton:(id)sender;
#end
And here is my WebViewController.m file:
#import "WebViewController.h"
#implementation WebViewController
#synthesize webView = _webView;
#synthesize webAddress = _webAddress;
#synthesize webURL = _webURL;
// Dismiss WebViewController
- (IBAction) doneButton:(id)sender {
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSURL* url = [webView.request URL];
_webAddress.text = [url absoluteString];
}
- (void)viewDidLoad
{
[_webView addSubview:activityIndicator];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_webURL]]];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:#selector(loading) userInfo:nil repeats:YES];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)loading {
if (!_webView.loading)
[activityIndicator stopAnimating];
else
[activityIndicator startAnimating];
}
- (void)viewDidUnload
{
_webURL = nil;
_webView = nil;
_webAddress = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)dealloc
{
[_webURL release];
[_webView release];
[_webAddress release];
[super dealloc];
}
#end
Does anybody know what I am doing wrong here? Thank you.
Use the - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType delegate instead. This will give you the actual request.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40006951-CH3-SW6
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL* url = [request URL];
_webAddress.text = [url absoluteString];
}
Related
How to change my profile picture image, when I click on done button in second screen the first screen image should change with the second screen image.
I am selecting image from Gallery that image was appearing in my second screen how to set this image in first screen view controller while I am clicking on done button.
This is MprofileViewController.h
#import <UIKit/UIKit.h>
#import "AddProfileViewController.h"
#class MProfileViewController;
#interface MProfileViewController : UIViewController<UIImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate,ImageSelectionDelegate>
{
NSMutableArray* titles;
IBOutlet UITableView *mainTableView;
IBOutlet UIImageView *image2;
}
#property(strong,nonatomic)IBOutlet UIImageView *image2;
#property(nonatomic, retain) NSMutableArray *titles;
#property(strong,nonatomic)UITableView *mainTableView;
-(IBAction) clickEventOnImage:(id) sender;
#end
MprofileViewController.m
#import "MProfileViewController.h"
#interface MProfileViewController ()
#end
#implementation MProfileViewController
#synthesize titles,mainTableView;
#synthesize image2;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
titles=[[NSMutableArray alloc]init];
self.navigationItem.title = #"View Profile";
image2.image=[UIImage imageNamed:#"hariku-indah.jpg"];
}
- (void) imageSelected:(UIImage *)image {
// Use image
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction) clickEventOnImage:(id) sender{
AddProfileViewController *Avc = [[AddProfileViewController alloc]initWithNibName:#"AddProfileViewController" bundle:nil];
Avc.delegate=self;
[self.navigationController pushViewController:Avc animated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:NO];
}
#end
AddProfileViewController.h
#import <UIKit/UIKit.h>
#protocol ImageSelectionDelegate <NSObject>
- (void) imageSelected:(UIImage*)image;
#end
#interface AddProfileViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate>{
IBOutlet UIImageView *imageView;
NSData *dataImage;
}
// Delegate property
#property (nonatomic,assign) id<ImageSelectionDelegate> delegate;
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
-(IBAction)back:(id)sender;
-(IBAction)done:(id)sender;
#end
AddprileViewController.m
#import "AddProfileViewController.h"
#import "MProfileViewController.h"
#interface AddProfileViewController ()
#property(strong,nonatomic) UIImagePickerController *imagePicker;
#end
#implementation AddProfileViewController
#synthesize imageView;
#pragma mark -
#pragma mark View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(#"actionSheet");
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 0) {
[self pushTakePhotoScreenInDelegate];
}
else if (buttonIndex == 1) {
[self pushChoosePhotoScreenInDelegate];
}
}
-(void)pushTakePhotoScreenInDelegate
{
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"viewfinder_2.png"]];
CGSize screenSize = [UIScreen mainScreen].bounds.size;
[imageView setFrame:CGRectMake(0, -52/2.0, screenSize.width, screenSize.height)];
self.imagePicker.cameraOverlayView = imageView;
self.imagePicker.delegate = self;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}
-(void)pushChoosePhotoScreenInDelegate
{
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imagePicker.delegate = self;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}
//-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
self.imageView.image = image;
[picker dismissViewControllerAnimated:YES completion:nil];
}
// In case you are using image picker, this delegate is called once image selection is complete.
//- (void)imagePickerController:(UIImagePickerController *)picker
//didFinishPickingMediaWithInfo:(NSDictionary *)info
//{
//Use either according to your setting, whether you allow image editing or not.
//self.imageView.image = image;
//UIImage *myImage = [info objectForKey:UIImagePickerControllerEditedImage];
//For edited image
// UIImage *myImage = [info objectForKey:UIImagePickerControllerOriginalImage];
//if([_delegate respondsToSelector:#selector(imageSelected:)]) {
// [self.delegate imageSelected:myImage];
// }
//}
/*
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage * pickedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
AddProfileViewController * controller = [AddProfileViewController new];
controller.imageView.image = pickedImage;
// [self.navigationController pushViewController:controller animated:YES];
}*/
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self.navigationController dismissModalViewControllerAnimated:YES];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Select Image from..."
delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Take Photo", #"Choose from library", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showInView:self.view];
}
-(IBAction)back:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)done:(id)sender
{
// if([_delegate respondsToSelector:#selector(imageSelected:)]) {
// [self.delegate imageSelected:imageView];
// }
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated{
[self.navigationController setNavigationBarHidden:YES];
}
#end
// if([_delegate respondsToSelector:#selector(imageSelected:)]) {
// [self.delegate imageSelected:imageView]; }
This code is technically correct. But you forgot to synthesize your delegate in AddprofileViewController
I'm trying to load any URL, after the initial load, in Safari. With any other webpage, this code works fine:
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL* url = [request URL];
if (UIWebViewNavigationTypeLinkClicked == navigationType)
{
[[UIApplication sharedApplication] openURL:url];
return NO;
}
return YES;
}
But as soon as I head over to m.youtube.com, the code no longer does anything, and YouTube continues to load inside the UIWebView. I can't find anything about this online. Any help?
Here is my entire .m file:
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize topLayer = _topLayer;
#synthesize layerPosition = _layerPosition;
#synthesize webView = webView;
#define VIEW_HIDDEN 260
- (void)viewDidLoad
{
[super viewDidLoad];
webView.delegate = self;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://m.youtube.com"]]];
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
webView.scrollView.bounces = NO;
webView.scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
[self performSelector:#selector(makeTick)];
self->promoteImages.contentSize = CGSizeMake(1920, 101);
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Scroll3.png"]];
[self->promoteImages addSubview:imageView];
[promoteImages setShowsHorizontalScrollIndicator:NO];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
return YES;
}
#end
And here's my .h file for the View Controller:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <Social/Social.h>
#interface SecondViewController : UIViewController <UIWebViewDelegate>
{
IBOutlet UIScrollView *promoteImages;
NSTimer *time;
IBOutlet UIWebView *webView;
}
#property (nonatomic, nonatomic) UIWebView *webView;
#property (weak, nonatomic) IBOutlet UIView *topLayer;
#property (nonatomic) CGFloat layerPosition;
#property(nonatomic,readonly,getter=isDragging) BOOL dragging;
#end
Here's the code that I use:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
return YES;
}
Here's your problem:
[[UIApplication sharedApplication] openURL:url];
Change to:
[[UIApplication sharedApplication] openURL:request.URL];
You can also specify only certain URLs to open in Safari, for example any URLS beginning with http://www.example.com/share as shown here:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ((navigationType == UIWebViewNavigationTypeLinkClicked) && ([currentURL hasPrefix:#"http://www.example.com/share"])) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
}
I'm finding it difficult to get started in Objective-C.
I'm executing the following code when a button is clicked:
NSLog(#"hi");
MainMenuDriver *mainMenuDriver= [[MainMenuDriver alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:mainMenuDriver animated:YES];
I can see "hi" in the console when I hit the button, it's just that the view should change to MainMenuDriver. But nothing happens!
Please help!
As per request for more code:
MainMenuDriver.h:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MainMenuDriver : UIViewController <UINavigationControllerDelegate,CLLocationManagerDelegate>{
IBOutlet UIButton *photos;
IBOutlet UIButton *profile;
IBOutlet UISwitch *onOffline;
IBOutlet UILabel *label1;
NSTimer *uploadGPS_timer;
CLLocationManager *lm;
NSString *lat;
NSString *lng;
}
#property(nonatomic,retain) UIButton *photos;
#property(nonatomic,retain) UIButton *profile;
#property(nonatomic,retain) UISwitch *onOffline;
#property(nonatomic,retain) UILabel *label1;
#property (nonatomic,retain) NSTimer *uploadGPS_timer;
#property(nonatomic,retain) NSString *lat,*lng;
-(IBAction)showMessages:(id)sender;
-(IBAction)showFriends:(id)sender;
-(IBAction)showPhotos:(id)sender;
-(IBAction)showProfile:(id)sender;
-(IBAction)switchSwitched:(id)sender;
-(void)uploadGPS_tick:(NSTimer*)timer;
#end
MainMenuDriver.m
#import "MainMenuDriver.h"
#import "ASIFormDataRequest.h"
#import "JoeMaxiViewController.h"
#import "Photos.h"
#import "Profile.h"
#implementation MainMenuDriver
#synthesize messages,profile,photos,friends,label1;
#synthesize onOffline;
#synthesize uploadGPS_timer;
#synthesize lat,lng;
-(IBAction)showPhotos:(id)sender{
[self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:nil action:nil]];
Photos *x= [[Photos alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:x animated:YES];
}
-(IBAction)showProfile:(id)sender{
[self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:nil action:nil]];
Profile *x= [[Profile alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:x animated:YES];
}
-(void)logout:(id)sender{
if([uploadGPS_timer isValid]){
[uploadGPS_timer invalidate];
}
[lm release];
//[uploadGPS_timer release];
[self.navigationController popViewControllerAnimated:NO];
/*NSString *urlStr=[[NSString alloc] initWithFormat:#"http://www.prestocab.com/driver/ajax/logout.php"];
NSURL *url=[NSURL URLWithString:urlStr];
__block ASIFormDataRequest *request=[[ASIFormDataRequest alloc ]initWithURL:url];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response=[request responseString];
NSLog(#"%#",response);
}];
[request setFailedBlock:^{
}];
[request startAsynchronous];*/
}
-(IBAction)switchSwitched:(id)sender{
if(onOffline.on){
[label1 setText:#"For Hire"];
[label1 setTextColor:[UIColor colorWithRed:0.0 green:0.8 blue:0.0 alpha:1.0]];
uploadGPS_timer=[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(uploadGPS_tick:) userInfo:nil repeats:YES];
[self uploadGPS_tick:nil];
}else{
[label1 setText:#"Engaged"];
[label1 setTextColor:[UIColor colorWithRed:0.8 green:0.0 blue:0.0 alpha:1.0]];
if([uploadGPS_timer isValid]){
[uploadGPS_timer invalidate];
}
}
}
-(void)uploadGPS_tick:(NSTimer*)timer{
if(!lat || !lng){
//do nothing
}else{
NSString *urlStr=[[NSString alloc] initWithFormat:#"http://www.prestocab.com/driver/ajax/updateCoords.php"];
NSURL *url=[NSURL URLWithString:urlStr];
__block ASIFormDataRequest *request=[[ASIFormDataRequest alloc ]initWithURL:url];
[request setPostValue:lat forKey:#"lat"];
[request setPostValue:lng forKey:#"lng"];
NSLog(#"EOH: %#",lat);
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response=[request responseString];
NSLog(#"%#",response);
//do nothing
}];
[request setFailedBlock:^{
//NSError *error =[request error];
//do nothing
}];
[request startAsynchronous];
}
}
-(void)locationManager:(CLLocationManager*) manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation*) oldLocation{
lat=[[NSString alloc]initWithFormat:#"%g",newLocation.coordinate.latitude];
lng=[[NSString alloc]initWithFormat:#"%g",newLocation.coordinate.longitude];
NSLog(#"%#,%#",lat,lng);
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
self.navigationItem.title=#"PrestoCab";
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:#"Logout" style:UIBarButtonItemStylePlain target:self action:#selector(logout:)];
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release];
//GPS
lm=[[CLLocationManager alloc] init];
if([CLLocationManager locationServicesEnabled]){
lm.delegate=self;
lm.desiredAccuracy=kCLLocationAccuracyBest;
lm.distanceFilter=30.0f;
[lm startUpdatingLocation];
}
//[self check4messages_tick:nil]; //want to start immediately, not in 10/40 seconds' time
[self uploadGPS_tick:nil];
//check4messages_timer=[NSTimer scheduledTimerWithTimeInterval:40.0 target:self selector:#selector(check4messages_tick:) userInfo:nil repeats:YES];
uploadGPS_timer=[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(uploadGPS_tick:) userInfo:nil repeats:YES];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
if([uploadGPS_timer isValid]){
[uploadGPS_timer invalidate];
}
}
-(void)dealloc{
[super dealloc];
[uploadGPS_timer release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Also, here is
MyClassViewController.h:
#import <UIKit/UIKit.h>
#interface MyClassViewController : UINavigationController{
IBOutlet UIButton *passenger;
IBOutlet UIButton *driver;
}
#property (nonatomic,retain) UIButton *passenger;
#property (nonatomic,retain) UIButton *driver;
-(IBAction) passengerClicked:(id)sender;
-(IBAction) driverClicked:(id)sender;
#end
and MyClassViewController.m:
#import "MyClassViewController.h"
#import "MainMenuDriver.h"
#implementation MyClassViewController
#synthesize passenger;
#synthesize driver;
-(IBAction)passengerClicked:(id)sender{
NSLog(#"passenger");
}
-(IBAction)driverClicked:(id)sender{
NSLog(#"driver");
MainMenuDriver *mainMenuDriver= [[MainMenuDriver alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:mainMenuDriver animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
I can see a couple of things:
Your nib file's name is different from the name of your class. If you put nil, the UIViewController will try to load a nib file with the UIViewController's name. Your UIViewController can be MainMenuDriver but your nib file name can be MainMenuDriverNibFileName.nib
[self navigationController] is nil.
For this, do the following:
NSLog(#"hi");
if([self navigationController]){
MainMenuDriver *mainMenuDriver= [[MainMenuDriver alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:mainMenuDriver animated:YES];
}
else{
NSLog(#"Houston we have a problem");
}
Update 1:
So, its nil, what you can do is the following:
Quick and Dirty:
[self presentViewController:mainMenuDriver animated:YES];
Instead of UIViewController switch to a UINavigationController.
The situation is very similar to that described by this my other question, except that the delegation seems to work fine. I'm providing some more detail about my code. I'm just striping out non-relevant/trivial parts.
ReportScreen.h
#interface ReportScreen : UIViewController <UIImagePickerControllerDelegate, UITextViewDelegate, MBProgressHUDDelegate, SoapDelegate, MapLocationChoiceDelegate>
// ...
#property (nonatomic, retain) MKPointAnnotation *annotation;
#property (nonatomic, retain) IBOutlet UITextView *textView;
#property (nonatomic, retain) IBOutlet UIButton *cameraButton;
#property (nonatomic, retain) IBOutlet UIButton *libraryButton;
#property (nonatomic, retain) IBOutlet UIButton *locationButton;
#property (nonatomic, retain) IBOutlet UIButton *sendButton;
#end
ReportScreen.m
#implementation ReportScreen
#synthesize annotation;
#synthesize textView;
#synthesize cameraButton;
#synthesize libraryButton;
#synthesize locationButton;
#synthesize sendButton;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Here I used to store the VC's state to a file but it shouldn't be needed now that I'm assigning it as delegate and said delegate seems to still be there even after a memory warning.
}
- (void)viewDidLoad {
[super viewDidLoad];
placeholderText = #"Tell us what's wrong…";
textView.text = placeholderText;
self.annotation = nil;
[self isReadyToSubmit];
hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:hud];
hud.delegate = self;
hud.labelText = #"Invio in corso…";
hud.dimBackground = YES;
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Here I used to restore the state of the VC from file but… y'know.
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self isReadyToSubmit];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:#"goToMap"]) {
MapScreen *vc = (MapScreen *)segue.destinationViewController;
// HERE's the magic
vc.mapLocationChoiceDelegate = self;
// MAGIC ends
if(self.annotation != nil) {
vc.annotations = [[NSMutableArray alloc] init];
[vc.annotations addObject:self.annotation];
}
}
}
- (BOOL)isReadyToSubmit {
if(self.annotation != nil) {
locationButton.highlighted = YES;
}
if(![textView.text isEqualToString:placeholderText] && self.annotation != nil) {
[sendButton setEnabled:YES];
} else {
[sendButton setEnabled:NO];
}
return [sendButton isEnabled];
}
- (void)textViewDidBeginEditing:(UITextView *)theTextView {
if([theTextView.text isEqualToString:placeholderText]) {
theTextView.text = #"";
}
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(didFinishEditing:)];
[self.navigationItem setRightBarButtonItem:done animated:YES];
}
- (void)textViewDidEndEditing:(UITextView *)theTextView {
if([theTextView.text isEqualToString:#""]) {
theTextView.text = placeholderText;
}
[self isReadyToSubmit];
}
- (void)didFinishEditing:(id)sender {
[self.navigationItem setRightBarButtonItem:nil animated:YES];
[self.textView resignFirstResponder];
}
// THIS is my delegate protocol's method
- (void)locationChosen:(MKPointAnnotation *)theAnnotation {
self.annotation = theAnnotation;
NSLog(#"R: %#", textView.text);
}
#end
MapScreen.h
#protocol MapLocationChoiceDelegate <NSObject>
- (void)locationChosen:(MKPointAnnotation *)annotation;
#end
// ---
#interface MapScreen : UIViewController <MKMapViewDelegate>
- (void)handleLongPress:(id)sender;
#property (nonatomic, retain) NSMutableArray *annotations;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property (weak) id<MapLocationChoiceDelegate> mapLocationChoiceDelegate;
#end
MapScreen.m
#implementation MapScreen
#synthesize annotations;
#synthesize mapView;
#synthesize mapLocationChoiceDelegate;
- (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)viewDidLoad {
[super viewDidLoad];
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0;
[self.mapView addGestureRecognizer:lpgr];
[mapView addAnnotations:self.annotations];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#pragma mark - Map handling
- (void)handleLongPress:(id)sender {
if(![sender isKindOfClass:[UILongPressGestureRecognizer class]]) {
return;
}
UILongPressGestureRecognizer *gr = (UILongPressGestureRecognizer *)sender;
if (gr.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [gr locationInView:self.mapView];
CLLocationCoordinate2D touchMapCoordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = touchMapCoordinate;
self.annotations = [NSMutableArray arrayWithArray:[mapView annotations]];
for(id a in self.annotations) {
if(![a isKindOfClass:[MKUserLocation class]]) {
[mapView removeAnnotation:a];
}
}
[mapView addAnnotation:annotation];
self.annotations = [NSMutableArray arrayWithArray:[mapView annotations]];
// NSDictionary *userInfo = [NSDictionary dictionaryWithObject:annotation forKey:#"annotation"];
// [[NSNotificationCenter defaultCenter] postNotificationName:#"PositionChosen" object:nil userInfo:userInfo];
[self.mapLocationChoiceDelegate locationChosen:annotation];
NSLog(#"M: %#", ((ReportScreen *)self.mapLocationChoiceDelegate).textView.text);
}
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
if([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
static NSString *AnnotationIdentifier = #"Annotation";
MKPinAnnotationView* pinView = (MKPinAnnotationView *)[theMapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (!pinView) {
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
} else {
pinView.annotation = annotation;
}
return pinView;
}
#end
The issue is:
ReportScreen pushes (performs segue to, actually) the MapScreen.
If I have some data in the UITextView or if I set some state to the buttons in the ReportScreen and I get a memory warning while the MapScreen is pushed, once I go back to the ReportScreen, all those fields don't show those settings. Apparently textView.text is still set, and so are the states of the buttons, they're just not shown.
Question: why?
Hi I am a beginner in programming
I have already created a tapping application, displaying the tap count after pressing the result button
I want to add a NSTimer, counting 30 second after the first tap (after the tap button was pressed for the first time).
at the same time, displaying the time count down on a label (UILabel timeLabel)
and after 30 second, the tap count will restart to 0.
Please kindly tell me if I need to post anything other than the following, Thanks!!
Here is my .h file
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
#import <AudioToolbox/AudioToolbox.h>
#class Player;
#interface Tapping2ViewController : UIViewController
<AVAudioPlayerDelegate>
{
Player *aPlayer;
IBOutlet UILabel *timerLabel;
IBOutlet UILabel *resultLabel;
AVAudioPlayer *buttonPlayer;
NSTimer *lv1Timer;
NSInteger *counter1;
}
- (IBAction)addTap:(id)sender;
- (IBAction)getResult:(id)sender;
-(void)restartTapCount;
-(void)start;
#property (retain) NSTimer *lv1Timer;
#property (nonatomic, retain) IBOutlet UILabel *timerLabel;
#end
and my .M file
#import "Tapping2ViewController.h"
#import "Player.h"
#implementation Tapping2ViewController
#synthesize lv1Timer;
#synthesize timerLabel;
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)dealloc
{
[resultLabel release];
[lv1Timer release];
[aPlayer release];
[timerLabel release];
[super dealloc];
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
aPlayer = [[Player alloc] init];
[super viewDidLoad];
}
- (IBAction)addTap:(id)sender
{
//呢到係設定聲音, 首先要用NSSTRING 去 SET 左條路徑先
NSString *buttonFile = [[NSBundle mainBundle] pathForResource:#"button" ofType:#"wav"];
//之後再條NSSTRING 轉做NSURL (因為AVPLAYER 只認URL)
NSURL *buttonFileURL = [NSURL fileURLWithPath:buttonFile];
NSError *error = nil;
//設定AUDIO PLAYER 要播邊條 聲音 *記得SET DELEGATE 做自已去執行
buttonPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:buttonFileURL error:&error];
[buttonPlayer setDelegate:self];
NSLog(#"Before: %d", aPlayer.tapCount);
aPlayer.tapCount++;
//呼叫播放既METHOD
[buttonPlayer play];
NSLog(#"After: %d", aPlayer.tapCount);
/*
//即時顯示數字
aPlayer.result = aPlayer.tapCount;
NSString *sResult = [NSString stringWithFormat:#"%D", aPlayer.result];
resultLabel.text = sResult;
*/
}
- (IBAction)getResult:(id)sender {
aPlayer.result = aPlayer.tapCount;
NSString *aResult = [NSString stringWithFormat:#"%D", aPlayer.result];
resultLabel.text = aResult;
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake)
{
aPlayer.tapCount = 0;
resultLabel.text = #"0";
}
}
- (void)viewDidUnload
{
[resultLabel release];
resultLabel = nil;
[timerLabel release];
timerLabel = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//下面係PART OF DETECT SHAKE 既METHOD
-(BOOL)canBecomeFirstResponder
{
return YES;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated
{
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
//去到呢到都係
#end
Here is how I do it in an app, on start :
count = COUNTDOWN_DURATION;
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self selector:#selector(countDown)
userInfo:nil repeats:YES];
this will call a countDown method every second. Do whatever you want in that countDown method but make sure to stop the NSTimer on completion (and of course to decrement counter):
if (count < 0) {
[countdownTimer invalidate];
countdownTimer = nil;
}
...
count--;