I'm having a problem with my search alert when using the search-tab. When someone is typing their search-string and hit return it will only dismiss the keyboard and you still have to tab the "Search" (Zoek) button do actually start a websearch.
Here is my code:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] >= 1 )
{
[searchview addSubview:indicator];
NSString *urlAddress= #"http://www.sportdirect.com/articles?search=";
urlAddress =[urlAddress stringByAppendingString:inputText];
NSURL *url= [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj= [NSURLRequest requestWithURL:url];
[searchview loadRequest:requestObj];
[[searchview scrollView] setBounces: NO];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:#selector(loading) userInfo:nil repeats:YES];
[TestFlight passCheckpoint:#"Voerde zoekopdracht uit"];
}
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
[_message dismissWithClickedButtonIndex:(0) animated:YES];
NSString *inputText = [[_message textFieldAtIndex:0] text];
if( [inputText length] >= 1 )
{
[searchview addSubview:indicator];
NSString *urlAddress= #"http://www.sportdirect.com/articles?search=";
urlAddress =[urlAddress stringByAppendingString:inputText];
NSURL *url= [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj= [NSURLRequest requestWithURL:url];
[searchview loadRequest:requestObj];
[[searchview scrollView] setBounces: NO];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:#selector(loading) userInfo:nil repeats:YES];
[TestFlight passCheckpoint:#"Voerde zoekopdracht uit"];
}
[textField resignFirstResponder];
return NO; // We do not want UITextField to insert line-breaks.
}
Does anyone know how to actually do a search as soon as the return button on the keyboard is tabbed?
Thanks in advance!
Your class needs to implement the UITextFieldDelegate to get the keyboard return callback. As suggested by borrden, this can be done as follows
[message textFieldAtIndex:0].delegate = self;
Then implement this method,
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// Dismiss the alert view
// Initiate the search
return YES;
}
Use this UIAlertView method. Refer Apple docs
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated
Call this on your alert view instance when required to dismiss it programmatically. You would require to keep message as an ivar to access it when required.
Hope that helps!
You can do this in UITextField delegate method:
your class must implement UITextFieldDelegate. set textField.delegate = self;
After implement this method:
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
// here you can write what you want, for example search
[textField resignFirstResponder];
return NO; // We do not want UITextField to insert line-breaks.
}
Related
I have a downloader in which I am trying to get the pasted text in my search bar to start downloading on tapping the return key.
How would I get the search bar to send a request to the pasted text to initialize the download?
What I'm calling:
NSString *pasteboardString = searchBar.text;
NSURL *url = [NSURL URLWithString:pasteboardString];
What needs to get triggered:
[self downloadURL:*HAS TO BE URL* userInfo:nil];
Any help is appreciated, thank you.
So I ended up figuring it out. In case somebody finds this useful.
#pragma mark - Firing Download
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
dispatch_async(dispatch_get_main_queue(), ^
{
// Do the search...
NSURL *url = [NSURL URLWithString:searchBar.text];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
bool valid = [NSURLConnection canHandleRequest:req];
if(valid)
{
[self downloadURL:url userInfo:nil];
NSLog(#"Valid URL - %#",searchBar.text);
[searchBar resignFirstResponder];
[searchBar setText:nil];
}
else
{
[alert showError:#"Enter valid url"];
[searchBar becomeFirstResponder];
[searchBar setText:nil];
}
});
NSLog(#"Search Button Pressed");
}
I am loading a webview with some url using:
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://abc-ecatalogue.xyz-ar.com/"]]];
then i am checking if the home page is being loaded then i dont want the navigation bar for this i am using:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// Here you can check the URL
NSURL *url = [request URL];
NSString*str=#"http://abc-ecatalogue.xyz-ar.com";
if ([url.absoluteString isEqualToString:#"http://havells-ecatalogue.adstuck-ar.com/"])
{
self.navigationController.navigationBarHidden = YES;
NSLog(#"hello");
return NO;
}
else
{
self.navigationController.navigationBarHidden = NO;
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style: UIBarButtonItemStyleBordered target:self action:#selector(Back)];
self.navigationItem.leftBarButtonItem = backButton;
}
return YES;
}
but when the control goes inside the loop the web view is not loaded and the log which i have printed is continously printed.
You have self.navigationController.navigationBarHidden = NO; in both the if & else part. You should change it to YES in the if section.EDIT:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// Here you can check the URL
NSURL *url = [request URL];
NSString*str=#"http://abc-ecatalogue.xyz-ar.com";
if ([url.absoluteString isEqualToString:#"http://havells-ecatalogue.adstuck-ar.com/"]) {
self.navigationController.navigationBarHidden = YES;
NSLog(#"hello");
} else {
self.navigationController.navigationBarHidden = NO;
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style: UIBarButtonItemStyleBordered target:self action:#selector(Back)];
self.navigationItem.leftBarButtonItem = backButton;
}
return YES;
}
I dived into learning apps development couple days ago and faced my first problem. Basically what I'm trying achieve is to hide and disable back button when there is no UIWebView history. Here is my code:
-(IBAction)backButtonPressed:(id)sender {
[webView goBack];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [[NSURL alloc] initWithString:#"http://nearom.com"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[self.webView loadRequest:request];
}
- (void) backButton{
if(webView.canGoBack == YES)
{
back.enabled = YES;
back.width = 0;
back.title = #"back";
}
else {
back.enabled = NO;
back.width = 0.01;
back.title = nil;
}
}
- (void)webViewDidFinishLoad:(UIWebView *)thisWebView{
[self backButton];
}
But backButton method isn't working. Could anybody explain what I'm doing wrong?
You might want to add more of your code. The only strange thing I have seen is that you use a parameter width. What do you want to do with that?
What I can not see from your code is if you have assigned the webviewDelegate to self so that webViewDidFinishLoad gets called.
Assuming you have a Navigation Controller, you should do the following:
self.navigationController.navigationItem.hidesBackButton = TRUE;
I am trying to present a camera view controller with a custom overlay containing two labels. I have been unable to get my imagePickerControllerDidCancel method and alertView to work properly. The system is printing the correct information to the NSLog but the lines of code that I have written are not doing anything and when the user taps 'Back' (to cancel the alertView and return to the imagePicker) the camera appears again but the takePhoto button and Cancel button are no longer accessible. They can still be seen but not tapped. When the user clicks the button at index 1 (Leave) I want the camera to be dismissed and to take the user back to my homeViewController which is at tabBarController index:1. In addition, when the camera first loads, the timerLabel is displayed with the correct data but then quickly disappears. I feel it has something to do with my refreshLabel method but again, I do not clearly understand where I am going wrong. None of these things are working for me and I'm still very new to the programming world so help with any of these matters would be greatly appreciated. thanks!
#import "CameraViewController.h"
#import "FriendsViewController.h"
#import <mobileCoreServices/UTCoreTypes.h>
#interface CameraViewController ()
#end
#implementation CameraViewController
#synthesize titleLabel;
#synthesize timerLabel;
- (void)viewDidLoad
{ [super viewDidLoad];
self.recipients = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (self.image == nil && [self.videoFilePath length] == 0) {
self.imagePickerController = [[UIImagePickerController alloc] init];
self.imagePickerController.delegate = self;
self.imagePickerController.allowsEditing = NO;
self.imagePickerController.videoMaximumDuration = 10;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;}
self.imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:self.imagePickerController.sourceType];
[self presentViewController:self.imagePickerController animated:NO completion:nil];}
[[NSBundle mainBundle] loadNibNamed:#"OverlayView" owner:self options:nil];
self.overlayView.frame = CGRectMake(160,8,0,0);
self.imagePickerController.cameraOverlayView = self.overlayView;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt",
documentsDirectory];
NSString *name = [NSString stringWithFormat:#"%#/name.txt",
documentsDirectory];
NSError *fileError;
titleLabel.text = [NSString stringWithContentsOfFile:name
encoding:NSASCIIStringEncoding
error:&fileError];
timerLabel.text = [NSString stringWithContentsOfFile:deadline
encoding:NSASCIIStringEncoding
error:&fileError];
if(fileError.code == 0){
NSLog(#"deadline.txt was read successfully with these contents: %#,",
timerLabel.text);
NSLog(#"name.txt was read successfully with these contents: %#,",
titleLabel.text);}
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(refreshLabel)
userInfo:nil
repeats:YES];
}
-(void)refreshLabel;{
self.formatter = [NSDateFormatter new];
[self.formatter setDateFormat:#"dd:hh:mm:ss"];
NSDate *startDate = [self.formatter dateFromString:self.timerLabel.text];
NSDate *timeLeft = [startDate dateByAddingTimeInterval:-1];
NSTimeInterval totalCountdownInterval = -1;
NSTimeInterval elapsedTime = [timeLeft timeIntervalSinceNow];
NSTimeInterval remainingTime = totalCountdownInterval - elapsedTime;
if (remainingTime <= 0.0) {
//dismiss controller and set to homecontroller at tabBar index 1
}
self.timerLabel.text = [self.formatter stringFromDate:timeLeft];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Are you Sure?"
message:#"you can't come back"
delegate:self cancelButtonTitle:#"Back" otherButtonTitles:#"Yes", nil];
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==1) {
[self.imagePickerController dismissViewControllerAnimated:NO completion:nil];
[self.tabBarController setSelectedIndex:1];
NSLog(#"Leave clicked");
}
else {
[self reset];
NSLog(#"cancel clicked");
}
}
- (void)reset {
self.image = nil;
self.videoFilePath = nil;
}
im curently working on a school project and my iphone app has been rejected twice and I know why. the solution to my problem though is tough. here i have the .m file from my project and I have a web based app. right now, if there is only http:// in the address bar, it displays an error that says the url's host is not found because it is only http:// and my app was rejected for that. what I want it to do is when only http:// is in the address bar, to make it go to a different web site. PLEASE HELP!! Plus I'm on iOS 6
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(void)bannerViewDidLoadAd:(ADBannerView *)banner{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:1];
[UIView commitAnimations];
}
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:0];
[UIView commitAnimations];
}
-(IBAction)press {
label.hidden = 0;
addressBar.hidden = 0;
browserPlace.hidden = 1;
button.hidden = 1;
button2.hidden = 0;
}
-(IBAction)press2
{
label.hidden = 1;
addressBar.hidden = 1;
browserPlace.hidden = 0;
button.hidden = 0;
button2.hidden = 1;
}
- (void)viewDidLoad
{
label.hidden = 1;
addressBar.hidden = 1;
browserPlace.hidden = 0;
button.hidden = 0;
button2.hidden = 1;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
addressBar.text = [defaults objectForKey:#"history"];
[self searchBarSearchButtonClicked:addressBar];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
[browserPlace loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[self parseUrl:addressBar.text]]]];
}
-(NSString*) parseUrl: (NSString*) url
{
if ([url hasPrefix:#"http://"] || [url hasPrefix:#"https://"])
return url;
else
return [NSString stringWithFormat:#"http://%#", url];
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
-(void)webViewDidStartLoad:(UIWebView *)webView
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:addressBar.text forKey:#"history"];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
label2.hidden = 0;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
label2.hidden = 1;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"%#", [error description]);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
label2.hidden = 1;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[error description] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Update your parseUrl: method. Check to see if the URL is just "http://":
- (NSString *)parseUrl:(NSString *)url {
if (url.length == 0 || [url isEqualToString:#"http://"]) {
return #"http://www.someplacecool.com"; // put your desired URL here
} else if ([url hasPrefix:#"http://"] || [url hasPrefix:#"https://"]) {
return url;
} else {
return [NSString stringWithFormat:#"http://%#", url];
}
}
You should also add other error checking in case the user enters any other invalid URLs.
I think you can make use of
(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
You can check the [request URL] and also its scheme.
Try to redirect the URL to different one in this method and return the respective BOOL value (YES/NO).