iOS Reachability error will not display - iphone

I have created an error message that should display if the user can not connect to google.com by either WI-FI or WWAN. I do not get any coding errors, so nothing seems to be wrong. I am using a UIWebview that goes to twitter.com. The issue may be that I am trying to get the error to display when the view loads and not the UIWebview, but I am not sure. Another issue that I am having is that I can not get "reachability" recognized as a name in the TwitterViewController.h file. Here is the code:
TwitterViewController.h
#import <UIKit/UIKit.h>
#import "Reachability.h"
#interface TwitterViewController : UIViewController {
Reachability *reachability;
}
#end
TwitterViewController.m
#import "TwitterViewController.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <netinet/in.h>
#import "TwitterView.h"
#implementation TwitterViewController
- (void)viewDidLoad {
[super viewDidLoad];
Reachability *r = [Reachability reachabilityWithHostName:#"http://www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
UIAlertView *NEalert = [[UIAlertView alloc] initWithTitle: #"Error"
message: #"Could not load the webpage. Please check your internet connection."
delegate: nil
cancelButtonTitle: #"Dismiss"
otherButtonTitles: nil];
[NEalert show];
[NEalert release];
}
}
#pragma mark -
#pragma mark Memory Management
- (void)dealloc {
[super dealloc];
}
#pragma mark -
#pragma mark Initialisation
- (id)init {
self = [super init];
if (self) {
self.hidesBottomBarWhenPushed = YES;
UINavigationBar objects
self.title = #"Twitter";
UIView *twitterView = [[TwitterView alloc] initWithParentViewController:self];
self.view = twitterView;
[twitterView release];
}
return self;
}
#pragma mark -
#pragma mark Action Methods
- (void)twitterBUTTONAction {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"NFAGaming's Twitter"
message: #"To follow NFAGaming on twitter, go to: twitter.com/NFAGaming"
delegate: nil
cancelButtonTitle: nil
otherButtonTitles: #"Ok", nil];
[alert show];
[alert release];
}
#pragma mark -
#pragma mark UIViewController Delegates
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#end
EDIT:
This is what ended up working perfectly for me
{{Reachability *r = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if (internetStatus == NotReachable) {
UIAlertView *tNEalert = [[UIAlertView alloc] initWithTitle: #"Error"
message: #"Internet Connection Required"
delegate: self
cancelButtonTitle: #"Dismiss"
otherButtonTitles: nil];
[tNEalert show];
[tNEalert release];
}
else {
UIView *twitterView = [[TwitterView alloc] initWithParentViewController:self];
self.view = twitterView;
[twitterView release];
}
}}

I used to use reachability like this:
self.reachability = [Reachability reachabilityForInternetConnection];
if ( [self.reachability currentReachabilityStatus] == NotReachable) {
UIAlertView *noConnectionAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Alert",#"Alert Title")
message:#"Internet connection is required." delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[noConnectionAlert show];
[noConnectionAlert release];
}
Use should use reachabilityWithHostName: only if you need to determine reachability to a specific host. See if this will work.

Related

Assigning to 'id<MFMessageComposeViewControllerDelegate>' from incompatible type 'MainViewController *'

I have the following warning in my code (XCode 4.3 / iOS 4/5) -
Assigning to 'id' from incompatible type 'MainViewController *'
The warning is raised in this section -
- (IBAction)sendInAppSMS:(id)sender
{
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = #"A test message from http://www.macoscoders.com";
controller.recipients = [NSArray arrayWithObjects:#"9880182343",nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
In particular this line -
controller.messageComposeDelegate = self;
In a bit confused as to what is wrong with my code. Googling for the Warning I found some references but I'm having difficulty in understanding the answers.
Any pointers / explanations would be greatly appreciated.
Best regards
rob
My complete .h file -
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <MessageUI/MessageUI.h>
#import "EasyTracker.h"
#interface MainViewController : TrackedUIViewController <MFMailComposeViewControllerDelegate> {
IBOutlet UIView *volumeSlider;
AVPlayer *radiosound;
IBOutlet UIButton *playpausebutton;
IBOutlet UIActivityIndicatorView *activityIndicator;
NSTimer *timer;
}
#property(nonatomic, retain) AVPlayer *radiosound;
#property(nonatomic, retain) UIButton *playpausebutton;
- (void)updatebuttonstatus;
- (void)playCurrentTrack;
- (void)pauseCurrentTrack;
- (IBAction)playbutton;
- (IBAction)openMail:(id)sender;
- (IBAction)sendInAppSMS:(id)sender;
#end
Highlights from my .m file -
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <MediaPlayer/MediaPlayer.h>
#import "radio99AppDelegate.h"
#implementation MainViewController
- (IBAction)sendInAppSMS:(id)sender
{
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = #"A test message from http://www.macoscoders.com";
controller.recipients = [NSArray arrayWithObjects:#"9880182343",nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
switch (result) {
case MessageComposeResultCancelled:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"SMSTester" message:#"User cancelled sending the SMS"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
break;
case MessageComposeResultFailed:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"SMSTester" message:#"Error occured while sending the SMS"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
break;
case MessageComposeResultSent:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"SMSTester" message:#"SMS sent successfully..!"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
break;
default:
break;
}
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)openMail:(id)sender
{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"A Message from MobileTuts+"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"fisrtMail#example.com", #"secondMail#example.com", nil];
[mailer setToRecipients:toRecipients];
UIImage *myImage = [UIImage imageNamed:#"mobiletuts-logo.png"];
NSData *imageData = UIImagePNGRepresentation(myImage);
[mailer addAttachmentData:imageData mimeType:#"image/png" fileName:#"mobiletutsImage"];
NSString *emailBody = #"Have you seen the MobileTuts+ web site?";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Your device doesn't support the composer sheet"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
}
}
#pragma mark - MFMailComposeController delegate
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled: you cancelled the operation and no email message was queued");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved: you saved the email message in the Drafts folder");
break;
case MFMailComposeResultSent:
NSLog(#"Mail send: the email message is queued in the outbox. It is ready to send the next time the user connects to email");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail failed: the email message was nog saved or queued, possibly due to an error");
break;
default:
NSLog(#"Mail not sent");
break;
}
[self dismissModalViewControllerAnimated:YES];
}
#end
You are using:
MFMailComposeViewControllerDelegate
Where it should be:
MFMessageComposeViewControllerDelegate
Change here:
#interface MainViewController : TrackedUIViewController <MFMessageComposeViewControllerDelegate> {
Implement the UINavigationControllerDelegate in your header file.
didn't work with this library, but as I can see, youe MainViewController is MF*Mail*ComposeViewControllerDelegate, but you setting it as MF*Message*ComposeViewControllerDelegate.

Cannot show UIAlertView with a text field

This piece of code which is supposed to show an alert window with a text input:
self.alert = [[UIAlertView alloc] initWithTitle:#"Hello" message:#"How are you?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
self.alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[self.alert show];
Causes this error:
Thread 7: Program received signal: "EXC_BAD_ACCESS"
This is how self.alert is defined:
#interface MyClass : NSObject
{
UIAlertView *alert;
id <MyClassDelegate> __unsafe_unretained delegate;
}
#property (nonatomic, retain) UIAlertView *alert;
#property (unsafe_unretained) id <MyClassDelegate> delegate;
The problem is maybe because of the customize.
I do not know why, but appear to me that the problem is because of the use of threads + customize of your alert.
Can you try to show this alert on the main thread? What happen?
You probably get an error in this line:
self.alert.alertViewStyle = UIAlertViewStylePlainTextInput;
What you need to do if yes, is perform this in the main thread.
- (void) yourMethod{
[self performSelectorOnMainThread:#selector(yourMethod2) withObject:nil waitUntilDone:NO];
}
- (void) yourMethod2{
self.alert = [[UIAlertView alloc] initWithTitle:#"Hello" message:#"How are you?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
self.alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[self.alert show];
}
Sorry to can't help you more than that, but I do not know exactly what happen, but I already read about issues when editing things to show, in other threads.
Hope it help you!
The EXC_BAD_ACCESS is caused by accessing a released object. To avoid this make your call to UIAlertView kind of modal:
Function body:
-(void)checkSaving
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Do you want to add these results to your database?"
message:#"\n\n"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Save", nil];
alert.alertViewStyle = UIAlertViewStyleDefault;
[alert show];
//this prevent the ARC to clean up :
NSRunLoop *rl = [NSRunLoop currentRunLoop];
NSDate *d;
d= (NSDate*)[d init];
while ([alert isVisible])
{
[rl runUntilDate:d];
}
}
Your choice result:
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 1)//Save
{
//do something
}
if (buttonIndex == 0)//NO
{
//do something
}
}
Register the functions in the interface declaration:
#interface yourViewController ()
-(void)checkSaving
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//...
#end
To call:
[self checkSaving];
I wish this will help you.

iphone alertview with textfield

I have an UIAlertView with a UITextField in it. I want to type the mail id and submit in UIAlertView's ok button, but UITextField in the UIAlertView have no response, Please help me.
thankz
From iOS 5 the approach above is no longer necessary. Just set the alertViewStyle property to the appropriate style (UIAlertViewStyleSecureTextInput, UIAlertViewStylePlainTextInput, or UIAlertViewStyleLoginAndPasswordInput).
Example:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Email" message:#"Enter your email:" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alertView show];
and you can have the response back as
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UITextField *emailTextField = [alertView textFieldAtIndex:0];
NSLog(#"%#",emailTextField.text);
}
UIAlertView with UITextField:
Usage:
NSString *title = NSLocalizedString(#"Your Title","");
NSString *placeholder = NSLocalizedString(#"Placeholder Text","");
NSString *message = NSLocalizedString(#"A message to the user.","");
NSString *cancel = NSLocalizedString(#"Cancel","");
NSString *okay = NSLocalizedString(#"Continue","");
prompt = [[AlertPrompt alloc] initWithTitle:title
placeholder:placeholder
message:message
delegate:self
cancelButtonTitle:cancel
okButtonTitle:okay];
[prompt show];
[prompt release];
.h
#import <Foundation/Foundation.h>
#interface AlertPrompt : UIAlertView <UITextFieldDelegate>
{
UITextField *textField;
NSString *enteredText;
}
#property(nonatomic,retain) UITextField *textField;
#property (nonatomic, retain, readonly) NSString *enteredText;
- (id)initWithTitle:(NSString *)title placeholder:(NSString *)placeholder message:(NSString *)message delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle okButtonTitle:(NSString *)okayButtonTitle;
#end
.m
#import ".h"
#implementation AlertPrompt
#synthesize textField;
#synthesize enteredText;
#pragma mark -
#pragma mark AlertPrompt Delegates
- (id)initWithTitle:(NSString *)title placeholder:(NSString *)placeholder message:(NSString *)message delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle okButtonTitle:(NSString *)okayButtonTitle {
if (self = [super initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:okayButtonTitle, nil])
{
self.title = title;
self.message = [NSString stringWithFormat:#"%#\n\n\n",message];
self.delegate = delegate;
UITextField *theTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 75.0f, 260.0, 30.0)];
[theTextField setBackgroundColor:[UIColor clearColor]];
theTextField.borderStyle = UITextBorderStyleRoundedRect;
theTextField.textColor = [UIColor blackColor];
theTextField.font = [UIFont systemFontOfSize:18.0];
theTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
theTextField.keyboardAppearance = UIKeyboardAppearanceAlert;
theTextField.returnKeyType = UIReturnKeyDone;
theTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
theTextField.placeholder = placeholder;
theTextField.delegate = self;
[self insertSubview:theTextField atIndex:0];
self.textField = theTextField;
[theTextField release];
CGAffineTransform translate = CGAffineTransformMakeTranslation(0, -10);
[self setTransform:translate];
}
return self;
}
- (void)show{
[textField becomeFirstResponder];
[super show];
}
- (NSString *)enteredText{
return textField.text;
}
- (void)dealloc{
[textField resignFirstResponder];
[textField release];
[super dealloc];
}
#end
Delegate:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.title isEqualToString:#"Your Title"])
{
if(buttonIndex == 1)
{
/* get the user iputted text */
NSString *inputValue = [(AlertPrompt *)alertView enteredText];
NSLog(#"User Input: %#",inputValue);
{
}
}
UIAlertView *emailAlert=[[UIAlertView alloc]initWithTitle:#"Enter your Email-id" message:#"\n\n" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK",nil];
emailTextField=[[UITextField alloc]initWithFrame:CGRectMake(12,45,260,25)];
[emailTextField becomeFirstResponder];
[emailTextField setBackgroundColor:[UIColor whiteColor]];
emailTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
emailTextField.placeHolder=#"Email";
[emailAlert addSubview:emailTextField];
[emailAlert show];
[emailAlert release];
Use UIAlertView Delegates Methods when OK button is clicked.
Swift version:
var alert = UIAlertView(title: "PostActionTitle", message: "PostActionText", delegate: self, cancelButtonTitle:"PostActionDecline")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
alert.addButtonWithTitle("PostActionAccept")
alert.show()

UIAlertView not responding to UIAlertViewDelegate

I'm using logos for iPhone (MobileSubstrate addons), with a .h file for my
#interface MyClass : NSObject <UIAlertViewDelegate>
and the
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
is in the .m, but nothing is working, when tapping the buttons on the alert, it doesn't invoke what I have set for each buttonIndex.
Thanks.
Edit: Here's what I've got;
#import "Tweak.h"
%hook ASApplicationPageHeaderView
- (void)_showPurchaseConfirmation {
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:#"title"];
[alert setMessage:#"message"];
[alert setDelegate:self];
[alert addButtonWithTitle:#"button 1"];
[alert addButtonWithTitle:#"continue"];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) { //also tried (UIAlertView *)alertView
UIAlertView *lol = [[UIAlertView alloc] init];
[lol setTitle:#"button 1"];
[lol setMessage:#"button 1"];
[lol setDelegate:self];
[lol addButtonWithTitle:#"lol"];
[lol show];
[lol release];
} else {
%orig;
}
}
%end
You'll most likely need to register your class as the delegate at some point using something along the lines of:
[yourAlertViewObject setDelegate:self];
As the UIAlertViewDelegate Protocol Reference docs say (emphasis mine):
If you add your own buttons or
customize the behavior of an alert
view, implement a delegate conforming
to this protocol to handle the
corresponding delegate messages. Use
the delegate property of an alert view
to specify one of your application
objects as the delegate.
Define your alert within that class and declare the alert delegate to self hope it start working to you
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert View "
"
message:#"Would you like to do something?"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Button1", #"Button2", nil];
[alert show];
[alert release];
You just need to put %new in front of the alertView delegate:
%new
-(void) alertView:...

persisting launchOptions NSURL as global variable

I have associated my app with a UTI so that users can launch KML attachments. In the iPad app delegate of my universal app I can see the launchOptions and from these I get an NSURL for the file being launched. I want to store this as a global so that I can access it from elsewhere in my app, I am doing this using a singleton called Engine. This is my App Delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
Engine *myEngine=[Engine sharedInstance];
StormTrackIpad *newVC=[[StormTrackIpad alloc] initWithNibName:#"StormTrackIpad" bundle:nil];
[window addSubview:newVC.view];
NSURL *launchFileURL=(NSURL *)[launchOptions valueForKey:#"UIApplicationLaunchOptionsURLKey"];
myEngine.launchFile=launchFileURL;
/* Show details of launched file
NSString *message =launchFileURL.absoluteString;
NSString *title = [NSString stringWithFormat:#"Opening file"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
*/
[window makeKeyAndVisible];
return YES;
}
My Engine class looks like this:
// Engine.h
#import <Foundation/Foundation.h>
#interface Engine : NSObject {
NSURL *launchFile;
}
+ (Engine *) sharedInstance;
#property (nonatomic, retain) NSURL *launchFile;
#end
// Engine.m
#import "Engine.h"
#implementation Engine
#synthesize launchFile;
static Engine *_sharedInstance;
- (id) init
{
if (self = [super init])
{
// custom initialization
}
return self;
}
+ (Engine *) sharedInstance
{
if (!_sharedInstance)
{
_sharedInstance = [[Engine alloc] init];
}
return _sharedInstance;
}
#end
My problem is that when I try to access the launchFile variable from the Engine elsewhere in my app (from a View Controller) the debugger shows the value of Engine.launchFile to be . I am accessing the variable like this:
- (void)viewDidLoad {
[super viewDidLoad];
Engine *myEngine=[Engine sharedInstance];
NSURL *launchFile=myEngine.launchFile;
NSString *title = [NSString stringWithFormat:#"Opening file"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:launchFile.absoluteString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
Any help?
Your code looks OK at first glance - can you set a breakpoint on myEngine.launchFile = just to see what myEngine is pointing at? This should make sure that your singleton code is working.
Also, have you checked that [launchOptions valueForKey:#"UIApplicationLaunchOptionsURLKey"] definitely returns an object? Did you mean to type this :
[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
Sam
P You should read the answer to this question on creating singleton objects, there's a few overrides that you should put into your Engine class ;)