xcode alertView tutorial returns blank on the simulator - uialertview

new to xcode and obj-c, i spend two day trying to solve this!
here's my alertViewController.h
#import <UIKit/UIKit.h>
#interface alert_ViewController : UIViewController <UIAlertViewDelegate>
#end
my alertViewController.m
#import "ViewController.h"
#implementation alert_ViewController
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
self.view.backgroundColor = [UIColor whiteColor];
NSString *message = #"Are you sure?";
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: #"Proceed?"
message:message
delegate:self
cancelButtonTitle: #"No"
otherButtonTitles: #"Yes", nil];
[alertView show];
}
#end
i run the project on the simulator and it comes up blank. any ideas?
thank you

Related

Xcode Point System Iphone Trivia Game

I am a beginner at creating iPhone apps and am trying to incorporate a simple point system for an iphone trivia game. Here is an basic overview of the app:
http://i.stack.imgur.com/nC0CI.png
So basically what I'm trying to do is make the user type the answer in the textfield. After typing an answer, they would click the button "Answer". If the answer is correct, an alert would show up saying "Correct", adding 100. If incorrect, it would say "Incorrect", subtracting 100.
However here is the problem: when you first answer correctly or incorrectly, the number remains at 0. When you click the button a second time, then it would properly increase/decrease. How do you fix this?
Here is my .h file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
NSString *stringpoint;
int point;
}
#property (nonatomic, retain) IBOutlet UITextField *textAnswer;
#property (nonatomic, retain) IBOutlet UILabel *pointlabel;
-(IBAction) checkAnswer;
#end
.m file
#synthesize textAnswer, pointlabel;
int point=0;
-(IBAction)checkAnswer {
pointlabel.text = [NSString stringWithFormat:#"%i",point];
if ([textAnswer.text isEqualToString:#"fruit"]) {
point=point+100;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Correct!"
delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[alert show];
[alert release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Incorrect"
delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
point=point-100;
[alert show];
[alert release];
}
}
I am using Xcode 4.3.
You are updating the label that shows points before you calculate the new total, just need to move it to after:
-(IBAction)checkAnswer {
// don't do this here, too early
// pointlabel.text = [NSString stringWithFormat:#"%i",point];
if ([textAnswer.text isEqualToString:#"fruit"]) {
point=point+100;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Correct!"
delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[alert show];
[alert release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Incorrect"
delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
point=point-100;
[alert show];
[alert release];
}
// now you've changed value of points above, so update the label
pointlabel.text = [NSString stringWithFormat:#"%i",point];
}

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.

iOS Reachability error will not display

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.

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 ;)