UIAlertView doesn't work - iphone

I have an alert view with the two buttons, but the buttons don't open the urls. I don't know the error. Help please.
Here's the code:
-(IBAction)showAlertView {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Obrir en..."
message:#"Es pot requirir la aplicació de Google Maps"
delegate:self
cancelButtonTitle:#"Millor no..."
otherButtonTitles:#"Mapes",#"Google Maps",nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Mapes"])
{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = #"http://maps.apple.com/?q=Plaça+del+Rei+43003+Tarragona";
NSURL *ourURL = [NSURL URLWithString:ourPath];
[ourApplication openURL:ourURL];
}
if([title isEqualToString:#"Google Maps"])
{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = #"comgooglemaps://?daddr=Plaça+del+Rei+43003+Tarragona&directionsmode=walking";
NSURL *ourURL = [NSURL URLWithString:ourPath];
[ourApplication openURL:ourURL];
}
}

I think the special character (ç) in the address is throwing the NSURL off. Try using the stringByAddingPercentEscapesUsingEncoding: method of NSString to encode it before passing it to the NSURL initializer.

Please check the URL which we fired.
if([ourApplication canOpenURL:ourURL])
[ourApplication openURL:ourURL];
else
NSLog(#"URL is not valid.");
As I check with both URL, they are not able to open.
You can check the URL with above code whether URL is able to open or not.

You have to check the URL's, try this:
-(IBAction)showAlertView {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Obrir en..."
message:#"Es pot requirir la aplicació de Google Maps"
delegate:self
cancelButtonTitle:#"Millor no..."
otherButtonTitles:#"Mapes",#"Google Maps",nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//0 is cancel
if(buttonIndex == 1)
{
[self openURLWithString:#"https://www.google.com/maps/preview#!q=Pla%C3%A7a+del+Rei+43003+Tarragona&data=!1m4!1m3!1d4618!2d1.2582895!3d41.1168719!4m11!1m10!4m8!1m3!1d26081603!2d-95.677068!3d37.0625!3m2!1i1024!2i768!4f13.1!17b1"];
}
if(buttonIndex == 2)
{
[self openURLWithString:#"https://www.google.com/maps/preview#!data=!1m4!1m3!1d18473!2d1.258181!3d41.1168316!4m13!3m12!1m0!1m1!1sPla%C3%A7a+del+Rei+43003+Tarragona!3m8!1m3!1d26081603!2d-95.677068!3d37.0625!3m2!1i1024!2i768!4f13.1&fid=0"];
}
}
- (void)openURLWithString:(NSString *)string{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = string;
NSURL *ourURL = [NSURL URLWithString:ourPath];
if([ourApplication canOpenURL:ourURL])
[ourApplication openURL:ourURL];
else
NSLog(#"URL is not valid.");
}

First, you should use elseif in your second condition, because you only want to fire the second if the first isn't true. Second, it seems to be the URL you're using in #"Mapes"... I tested this and that URL seems to be the culprit. When I changed that URL to another test URL, it worked.

Related

how to check in iphone app if url is valid then load in WebVIew else show alert

I have app in which i want that when user enter url in textfield and presses return key it should check if url is valid then load url in web view else show alert enter valid url
In my code it always show Valid URL.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(#"Test is working and test is %#",test);
[self urlIsValiad:test];
if ([test isEqualToString:#"Valid"]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please enter Valid URL" message:#"" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}
- (BOOL) urlIsValiad: (NSString *) url
{
NSString *regex =
#"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
/// OR use this
///NSString *regex = "(http|ftp|https)://[\w-_]+(.[\w-_]+)+([\w-.,#?^=%&:/~+#]* [\w-\#?^=%&/~+#])?";
NSPredicate *regextest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if ([regextest evaluateWithObject: url] == YES) {
NSLog(#"URL is valid!");
test=#"Valid";
} else {
NSLog(#"URL is not valid!");
test=#"Not Valid";
}
return [regextest evaluateWithObject:url];
}
// .h File
-(BOOL)validateUrl;
.m File
-(BOOL)validateUrl{
NSString *urlRegEx = #"((?:http|https)://)?(www\\.)[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
if ([urlTest evaluateWithObject: self] == YES) {
NSLog(#"URL is valid!");
} else {
NSLog(#"URL is not valid!");
}
return [urlTest evaluateWithObject:self];
}
// Main View Controller .m File
if (![txtWebsite.text validateUrl])
{
[KWebsiteURLTypeValidation showAsAlert:self];
return;
}
You can use this method:
- (BOOL) validateUrl: (NSString *) url {
NSString *theURL =
#"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", theURL];
return [urlTest evaluateWithObject:url];
}
From Check URL validity . Hope this helps.
i've modified your code so please replace this method with your code and it will work superfine
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(#"Test is working and test is %#",test);
if ([self urlIsValiad:test]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please enter Valid URL" message:#"" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}

Want to get my captured video back

I have created a camera using AVFoundation, now i want my video back so i can upload it on my server how can i do that ?
I am using MKNetworkKit for upload video on server.
I am getting output like this:
file://localhost/private/var/mobile/Applications/4B2E02E5-3EE2-493E-8ECF-4B1DA29B9387/tmp/output.mov
Guys I have figured out it by some help here is code for that.
- (void) captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)anOutputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
videodata = [NSData dataWithContentsOfURL:outputFileURL];
//NSLog(#"output file url is :%#",anOutputFileURL);
NSLog(#"output video data size is:%d", videodata.length);
if ([[self delegate] respondsToSelector:#selector(recorder:recordingDidFinishToOutputFileURL:error:)]) {
[[self delegate] recorder:self recordingDidFinishToOutputFileURL:anOutputFileURL error:error];
}
//NSLog(#"captureOutput is: %#",captureOutput);
// NSLog(#"anOutputFileURL is: %#",anOutputFileURL);
//videoPath = [NSString stringWithContentsOfURL:anOutputFileURL encoding:NSUTF8StringEncoding error:nil];
//videoPath = [anOutputFileURL absoluteString];
//videoURL = anOutputFileURL;
// videodata = captureOutput;
// NSLog(#"video path is: %#",videodata);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
message:#"Do you want to upload this content to the yes stream network ?"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
NSLog(#"Yes was selected.");
self.flUploadEngine = [[fileUploadEngine alloc] initWithHostName:#"manektech.net" customHeaderFields:nil];
NSMutableDictionary *postParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"testApp", #"appID",
nil];
self.flOperation = [self.flUploadEngine postDataToServer:postParams path:#"/dilipvideotest/savefile.php"];
[self.flOperation addData:videodata forKey:#"uploadfile" mimeType:#"video/mov" fileName:#"output.mov" ];
[self.flOperation onCompletion:^(MKNetworkOperation *operation) {
NSLog(#"response string is : %#", [operation responseString]);
/*
This is where you handle a successful 200 response
*/
}
onError:^(NSError *error) {
NSLog(#"error : %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}];
[self.flUploadEngine enqueueOperation:self.flOperation ];
}
else if([title isEqualToString:#"No"])
{
NSLog(#"No was selected.");
//[self readMovie:outputFileURL];
}
}

UIActionSheet isn't loading actions for button indexes?

I have set up some code so that when two separate buttons are tapped on a UIActionSheet, there will be two different actions. Unfortunately nothing happens when the buttons are pressed. The UIActionSheet just unloads as if a cancel button had been pressed.
Here's my code:
- (IBAction)saveFile:(id)sender {
UIActionSheet *saveFileSheet = [[[UIActionSheet alloc]
initWithTitle:#"iDHSB Download Centre"
delegate:nil
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Download File", #"Show My Files", nil]
autorelease];
[saveFileSheet showInView:webView];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(#"Action Sheet Button Pressed");
if(buttonIndex == 1) {
NSLog(#"Show My Files");
[self.window presentModalViewController:savedFiles animated:YES];
}
if(buttonIndex == 2){
NSLog(#"Saving File");
// Get the URL of the loaded ressource
NSURL *theResourcesURL = [[webView request] URL];
// Get the filename of the loaded ressource form the UIWebView's request URL
NSString *filename = [theResourcesURL lastPathComponent];
NSLog(#"Filename: %#", filename);
// Get the path to the App's Documents directory
NSString *docPath = [self documentsDirectoryPath];
// Combine the filename and the path to the documents dir into the full path
NSString *pathToDownloadTo = [NSString stringWithFormat:#"%#/%#", docPath, filename];
// Load the file from the remote server
NSData *tmp = [NSData dataWithContentsOfURL:theResourcesURL];
// Save the loaded data if loaded successfully
if (tmp != nil) {
NSError *error = nil;
// Write the contents of our tmp object into a file
[tmp writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];
if (error != nil) {
UIAlertView *filenameErrorAlert = [[UIAlertView alloc] initWithTitle:#"Error Saving" message:[NSString stringWithFormat:#"The file %# could not be saved. Please try again.", filename] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[filenameErrorAlert show];
[filenameErrorAlert release];
NSLog(#"Failed to save the file: %#", [error description]);
} else {
// Display an UIAlertView that shows the users we saved the file :)
UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:#"File saved" message:[NSString stringWithFormat:#"The file %# has been saved.", filename] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[filenameAlert show];
[filenameAlert release];
}
} else {
NSLog(#"Error, file could not be saved");
}
}
else
{
NSLog(#"Error, could not find button index!");
}
}
Thanks,
James
You have set the UIActionSheet delegate to nil. In this context, you want to set it to self.
You have to set the delegate to self
UIActionSheet *saveFileSheet = [[[UIActionSheet alloc]
initWithTitle:#"iDHSB Download Centre"
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Download File", #"Show My Files", nil]
autorelease];
You’re creating the action sheet with a nil delegate, so the delegate methods you implemented will never get called. Pass self as the delegate in the action sheet’s initializer and it should work.

Objective - C Connection Test Warnings

I have the following code:
//View guest list
-(IBAction) guestList:(id) sender{
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"myURL"]];
//Waits a set peroid of time
wait(20000);
//Guest list is availible
if (connected != NULL){
CHARLIEAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate displayView:6];
}
//No network connection availible
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Network Connection!" message:#"Cannot establish internet connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
And I get the following warnings:
//Waits a set peroid of time
wait(20000);
Gives me -
warning: passing argument 1 of 'wait' makes pointer from integer without a cast
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://photostiubhart.comoj.com/testconnection.php"]];
Gives me -
warning: 'stringWithContentsOfURL:' is deprecated (declared at /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSString.h:384)
I've done my testing and the code SEEMS to work fine, even though there are these warnings. Is there a way to remove these warnings at all? Or do they not matter?
I'm using xCode version 3.2.6
Thanks,
Jack
use
NSError* error;
NSString* connected = [NSString stringWithContentsOfURL:TheUrl encoding:NSASCIIStringEncoding error:&error];
You should use the method -
+(id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
for example -
NSString* text = [NSString stringWithContentsOfURL:TheUrl encoding:NSASCIIStringEncoding error:&error];
Hope it will help you.
Try doing it this way:
-(IBAction)guestList:(id) sender{
NSURL *requestUrl = [NSURL URLWithString:#"http://photostiubhart.comoj.com/testconnection.php"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:requestUrl];
NSData *loadTest = [NSData dataWithContentsOfURL:requestUrl];
if (loadTest == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Network Connection!" message:#"Cannot establish internet connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
} else {
CHARLIEAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate displayView:6];
}
}

Adding more than one confirmationalerts (UIAlertView)

Basically, what I try to do is to add multiple confirmationalerts...but I just cant get it to work. No matter what confirmationalert i press, the "Continue" button leads to the exact same thing (a body without text and a subject with "XXXX")...
Any idea how to make the confimationalerts to lead to different things?
EDIT 2; No matter what button I press (continue or dismiss), the app sends the user to mail.app...
-(IBAction)mail {
UIAlertView *mail = [[UIAlertView alloc] init];
[mail setTag:ALERTVIEW_MAIL_TAG];
[mail setTitle:#"Open mail"];
[mail setMessage:#"....."];
[mail setDelegate:self];
[mail addButtonWithTitle:#"Continue"];
[mail addButtonWithTitle:#"Dismiss"];
[mail show];
[mail release];
}
-(IBAction)feedback {
UIAlertView *feedback = [[UIAlertView alloc] init];
[feedback setTag:ALERTVIEW_TIPSA_TAG];
[feedback setTitle:#"Open mail"];
[feedback setMessage:#"....."];
[feedback setDelegate:self];
[feedback addButtonWithTitle:#"Continue"];
[feedback addButtonWithTitle:#"dismiss"];
[feedback show];
[feedback release];
}
- (void)showConfirmAlert
{
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if([alertView tag] == ALERTVIEW_FEEDBACK_TAG) {
NSURL *url = [[NSURL alloc] initWithString:#"mailto:?subject=XXXX"];
[[UIApplication sharedApplication] openURL:url];
[url release];
}
else if (buttonIndex == 1) {
}
else if ([alertView tag] == ALERTVIEW_MAIL_TAG) {
NSString *subject = #"YYYY";
NSString *body = #".....";
NSString *path = [NSString stringWithFormat:#"mailto:?subject=%#&body=%#", subject, body];
NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
}
else if (buttonIndex == 1) {
}
}
You'll need to set a tag on your UIAlertView objects and switch on them in your delegate method, this is why the delegate method takes in the UIAlertView, so you can do stuff based on which object the button was pressed.
#define ALERTVIEW_MAIL_TAG 100
#define ALERTVIEW_FEEDBACK_TAG 101
- (IBAction) feedback {
UIAlertView *feedback = [[UIAlertView alloc] init];
[feedback setTag:ALERTVIEW_FEEDBACK_TAG];
//...
}
- (IBAction) mail {
UIAlertView *mail = [[UIAlertView alloc] init];
[mail setTag:ALERTVIEW_MAIL_TAG];
}
-(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger) buttonIndex {
if([alertView tag] == ALERTVIEW_MAIL_TAG) {
//do stuff...
} else {
//do other stuff...
}
}
The delegate method is specified by the UIAlertViewDelegate protocol, you can't change that.
There are 2 things you can do:
Use 2 different delegates and specify a clickedButtonAtIndex-method for each class.
In the clickedButtonAtIndex-method first check which alertview has sended the message. This requires to tag the UIAlertView (see answer by Jacob Relkin) or to create an instance variable for each UIAlertView.
You should specify which of your buttons is the cancel button, and then you need to check which button was clicked and don't do anything if it was the cancel button. I.e., when you create the alert:
alertView.cancelButtonIndex = 1;
And when you get the button clicked message:
if (buttonIndex == alertView.cancelButtonIndex) return;