I have a button (Buy) to open up a UIView (viewInAppPurchases) on top of another UIView (viewMenu). The Buy button is in the UIView viewMenu. I also have a button (Close) in the UIView viewInAppPurchases.
In the code when clicking the close button in the viewInAppPurchases, it shall close the view and go back to the viewMenu. But when clicking on the Buy button again, nothing happens. It should reopen the viewInAppPurchases UIView.
What else should I add and/or change to the code so when the Buy button is clicked again, it shall open up the viewInAppPurchases again?
In Header file:
#property (strong, nonatomic) IBOutlet UIView *viewInAppPurchases;
In implementation .m file:
- (IBAction)buttonClose: (UIButton*)sender
{
[_viewInAppPurchases removeFromSuperview];
}
Below is the IAP as GaryRiches request. I noticed that I didn't have a "close button" instruction in the IAP itself, but only through the MenuViewController.
How do I put the close button instructions in it?
BuyView.h
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#import "MyIAPHelper.h"
#interface BuyView : UIView
{
SKProduct *product;
NSMutableArray *lstProducts;
int productIndex;
BOOL hasProducts;
}
#property (nonatomic, strong) UIViewController *parentViewController;
- (IBAction)buyCoin:(id)sender;
- (IBAction)shareTwitterGetCoin:(id)sender;
- (IBAction)shareFacebookGetCoin:(id)sender;
#end
BuyView.m
#import "BuyView.h"
#implementation BuyView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(productPurchased:)
name:IAPHelperProductPurchasedNotification object:nil];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
NSArray *nibs = [[NSBundle mainBundle]
loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
// NSArray *subviewArray = [[NSBundle mainBundle]
loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
UIView *mainView = [nibs objectAtIndex:0];
//Just in case the size is different (you may or may not want this)
mainView.frame = self.bounds;
[self addSubview:mainView];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(productPurchased:)
name:IAPHelperProductPurchasedNotification object:nil];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during
animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
- (IBAction)buyCoin:(id)sender {
BUTTON_SOUND
UIButton *btn = (UIButton *)sender;
NSString *productID = #"";
switch (btn.tag) {
case 0:
NSLog(#"buy 0.99");
productIndex = 0;
productID = FIRST_TIER;
break;
case 1:
NSLog(#"buy 1.99");
productIndex = 1;
productID = SECOND_TIER;
break;
case 2:
NSLog(#"buy 4.99");
productIndex = 2;
productID = THIRD_TIER;
break;
case 3:
NSLog(#"buy 9.99");
productIndex = 3;
productID = FOURTH_TIER;
break;
case 4:
NSLog(#"buy 19.99");
productIndex = 4;
productID = FIFTH_TIER;
break;
default:
break;
}
SKProduct *selectedProduct;
for (int i=0; i<lstProducts.count; i++) {
SKProduct *_product = [lstProducts objectAtIndex:i];
if ([_product.productIdentifier isEqualToString:productID]) {
selectedProduct = _product;
break;
}
}
[[MyIAPHelper shareInstance] buyProduct:selectedProduct];
}
- (void)productPurchased:(NSNotification *)notification {
NSLog(#"===========PurchaseViewController===========");
NSLog(#"purchased success");
//Add coin here IAPHelperProductPurchasedNotification
int increaCoin = 0;
switch (productIndex) {
case 0:
increaCoin = 100;
break;
case 1:
increaCoin = 250;
break;
case 2:
increaCoin = 750;
break;
case 3:
increaCoin = 2000;
break;
case 4:
increaCoin = 5000;
break;
default:
break;
}
NSString *strMsg = [NSString stringWithFormat:#"You have purchased
successfully and got %d coins",increaCoin];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Message" message:strMsg delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[self updateCoinWithIncreaseCoin:increaCoin];
}
- (void)updateCoinWithIncreaseCoin:(int)increaseCoin_{
int currentCoin = [Utils getCoin];
[Utils updateCoin:(currentCoin + increaseCoin_)];
}
- (IBAction)shareTwitterGetCoin:(id)sender {
BUTTON_SOUND
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
if (![userdefaults objectForKey:#"FIRST_SHARE_TWITTER"]) {
[userdefaults setObject:#"Abcd" forKey:#"FIRST_SHARE_TWITTER"];
[userdefaults synchronize];
SLComposeViewController *controller = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[controller setInitialText:#"Check out this new App!"];
[controller addURL:[NSURL URLWithString:APP_URL]];
[self.parentViewController presentViewController:controller
animated:YES completion:^{
//get coin here
NSLog(#"get coin share twitter");
int currentCoin = [Utils getCoin] + 30;
[Utils updateCoin:currentCoin];
}];
}
}
- (IBAction)shareFacebookGetCoin:(id)sender {
BUTTON_SOUND
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
if (![userdefaults objectForKey:#"FIRST_SHARE_FACEBOOK"]) {
[userdefaults setObject:#"Abc" forKey:#"FIRST_SHARE_FACEBOOK"];
[userdefaults synchronize];
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller setInitialText:#"Check out this new App!"];
[controller addURL:[NSURL URLWithString:APP_URL]];
[self.parentViewController presentViewController:controller animated:YES completion:^{
//add coin here
NSLog(#"get coin share facebook");
int currentCoin = [Utils getCoin] + 30;
[Utils updateCoin:currentCoin];
}];
}else{
}
}
#end
What else should I add and/or change to the code so when the Buy
button is clicked again, it shall open up the viewInAppPurchases
again?
You should add it back to the view from which you removed it.
You can do it on click event by:
[self.view addSubview: _viewInAppPurchases];
Also, have you consider hiding it instead of removing it completly and then adding it back?
To hide your view:
[_viewInAppPurchases setHidden:YES];
To show it again:
[_viewInAppPurchases setHidden:NO];
I changed the
removeFromSuperview
to
setHidden:Yes
and it did the trick.
Related
This is some code from my sms plugin for phonegap. I'm trying to make callbacks work properly: https://github.com/aharris88/phonegap-sms-plugin/issues/11
Here's the code I'm working on. You can see that I get the callback function at the beginning of the send method like this:
NSString* callback = command.callbackId;
Then I present an MFMessageComposeViewController and I need to call that callback when it finishes. So I'm using the messageComposeViewController:didFinishWithResult:, but how can I access that callback function that I need to call?
#import "Sms.h"
#import <Cordova/NSArray+Comparisons.h>
#implementation Sms
- (CDVPlugin *)initWithWebView:(UIWebView *)theWebView {
self = (Sms *)[super initWithWebView:theWebView];
return self;
}
- (void)send:(CDVInvokedUrlCommand*)command {
NSString* callback = command.callbackId;
if(![MFMessageComposeViewController canSendText]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Notice"
message:#"SMS Text not available."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return;
}
MFMessageComposeViewController* composeViewController = [[MFMessageComposeViewController alloc] init];
composeViewController.messageComposeDelegate = self;
NSString* body = [command.arguments objectAtIndex:1];
if (body != nil) {
[composeViewController setBody:body];
}
NSArray* recipients = [command.arguments objectAtIndex:0];
if (recipients != nil) {
[composeViewController setRecipients:recipients];
}
[self.viewController presentViewController:composeViewController animated:YES completion:nil];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
}
#pragma mark - MFMessageComposeViewControllerDelegate Implementation
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
int webviewResult = 0;
CDVPluginResult* pluginResult = nil;
switch(result) {
case MessageComposeResultCancelled:
webviewResult = 0;
break;
case MessageComposeResultSent:
webviewResult = 1;
break;
case MessageComposeResultFailed:
webviewResult = 2;
break;
default:
webviewResult = 3;
break;
}
[self.viewController dismissViewControllerAnimated:YES completion:nil];
[[UIApplication sharedApplication] setStatusBarHidden:NO];
if (webviewResult == 1) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:#"Arg was null"];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:callback];
}
#end
You'll want to store the callback ID as a property on the class.
#interface Sms
#property (nonatomic, strong) NSString *callbackId
#end
And then store it when you are in your send method.
- (void)send:(CDVInvokedUrlCommand*)command {
self.callbackId = command.callbackId;
You can then access it again from your delegate method:
NSString *callbackId = self.callbackId;
You should be good to go.
I made an AR app that recognize image and show the object recognized in an AlertView. In the AlertView I have 2 buttons: Add and Cancel, I'm using the UIAlertViewDelegate to understand which button the user pressed. If the user press the Add button, the object recognized will be stored in an array. I pass this array to another ViewController, in which I set up a TableView. On the bottom of this TableView there's a button "Pay" to go to another ViewController in which I display the total price of the object recognized. From the last ViewController I can press a button to pay the objects I selected by using the AR. Now when I press this button the app close this ViewController and go back to the first ViewController, but the array in which I stored the object that the AR recognized it's full. To delete the content of this array I thought that the best way is to use the delegation methods, so I made this:
PaymentViewController.h
#import <UIKit/UIKit.h>
#protocol PaymentViewControllerDelegate;
#interface PaymentViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *labelTotal;
- (IBAction)buttonClosePaymentVC:(id)sender;
- (IBAction)buttonPay:(id)sender;
#property(nonatomic,strong)NSString *total;
#property(assign) id<PaymentViewControllerDelegate> delegate;
#end
#protocol PaymentViewControllerDelegate <NSObject>
- (void)cleanReportArray;
#end
PaymentViewController.m
#import "PaymentViewController.h"
#interface PaymentViewController () <UIAlertViewDelegate>
#end
#implementation PaymentViewController
#synthesize delegate = _delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.labelTotal.text = self.total;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonClosePaymentVC:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)buttonPay:(id)sender {
NSString *pay = [NSString stringWithFormat:#"Stai per pagare %#, procedi?", self.total];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"HelloMS" message:pay delegate:self cancelButtonTitle:#"Si" otherButtonTitles:#"No", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
// Procedura per il pagamento e cancellazione del file plist
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"objects.plist"];
NSError *error;
if (![[NSFileManager defaultManager]removeItemAtPath:path error:&error]) {
NSLog(#"Errore: %#", error);
}
__weak UIViewController *vcThatPresentedCurrent = self.presentingViewController;
[self dismissViewControllerAnimated:YES completion:^{
[vcThatPresentedCurrent dismissViewControllerAnimated:YES completion:nil];
}];
[self.delegate cleanReportArray];
}
if (buttonIndex == 1) {
// Non deve far nulla: fa scomparire l'UIAlertView
}
}
Here I post to you the method of the class that will use the delegate:
Interface of the ScannerViewController.m
#interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
#property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
#end
In ViewDidLoad I inserted this rows:
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
And in the ScannerViewController.m I implemented the method I declared in PaymentViewController.h:
- (void)cleanReportArray {
[arrayObjectAdded removeAllObjects];
}
I tested my app on my iPhone, the app works fine until I try to pay the objects I scanned by camera, indeed, I tried to pay the object, but it doesn't clean the array in which I stored the objects scanned.
What's wrong in my code? I used an tutorial on the web to understand better how the delegation method works. I hope you can help me to fix this issue, thank you
UPDATE:
here i will post my ScannerViewController code:
ScannerViewController.h
#import <UIKit/UIKit.h>
#interface ScannerViewController : UIViewController
#end
ScannerViewController.m
#import "ScannerViewController.h"
#import "PaymentViewController.h"
#import "ReportViewController.h"
#import "MSScannerSession.h"
#import "MSResult.h"
#import "XmlReader.h"
static int kMSScanOptions = MS_RESULT_TYPE_IMAGE |
MS_RESULT_TYPE_EAN8 |
MS_RESULT_TYPE_EAN13;
#interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
#property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
#end
#implementation ScannerViewController {
MSScannerSession *_scannerSession;
NSString *nameOfObjectScanned;
XmlReader *reader;
NSMutableArray *arrayObjectAdded;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
_scannerSession = [[MSScannerSession alloc] initWithScanner:[MSScanner sharedInstance]];
[_scannerSession setScanOptions:kMSScanOptions];
[_scannerSession setDelegate:self];
}
return self;
}
- (void)session:(MSScannerSession *)scanner didScan:(MSResult *)result {
if (!result) {
return;
}
[_scannerSession pause];
NSString *resultStr = nil;
if (result) {
switch ([result getType]) {
case MS_RESULT_TYPE_IMAGE:
resultStr = [NSString stringWithFormat:#"Immagine trovata: %#", [result getValue]];
break;
case MS_RESULT_TYPE_EAN8:
case MS_RESULT_TYPE_EAN13:
resultStr = [NSString stringWithFormat:#"EAN trovato: %#", [result getValue]];
break;
default:
break;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
UIActionSheet *asView = [[UIActionSheet alloc]initWithTitle:resultStr delegate:self cancelButtonTitle:#"OK" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
asView.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[asView showInView:self.view];
[self addObjectToList:resultStr];
});
}
- (void)addObjectToList:(NSString *)objectName {
// Ricerca dell'oggetto
NSString *object = [objectName substringFromIndex:18];
if ([object isEqualToString:#"Binario_con_coppia"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Dadi_colorati"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Dadi_rossi"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Bici_da_corsa"]) {
[self showAlert:object];
}
}
- (void)showAlert:(NSString*)name {
name = [name stringByReplacingOccurrencesOfString:#"_" withString:#" "];
nameOfObjectScanned = name;
NSString *message = [NSString stringWithFormat:#"Ho riconosciuto questo oggetto: %#, vuoi aggiungerlo al carrello?", name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"HelloMS" message:message delegate:self cancelButtonTitle:#"Aggiungi" otherButtonTitles:#"Annulla", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSLog(#"Aggiungi");
for (int i = 0; i < [reader.objArray count]; i++) {
if ([[reader.objArray[i]objectForKey:#"name"] isEqualToString:nameOfObjectScanned]) {
// Salvo il nome dell'oggetto trovato, il prezzo e la descrizione
NSString *name = [reader.objArray[i]objectForKey:#"name"];
NSString *desc = [reader.objArray[i]objectForKey:#"desc"];
NSString *price = [reader.objArray[i]objectForKey:#"price"];
NSDictionary *newObjectAdded = [[NSDictionary alloc]init];
newObjectAdded = #{#"name": name,
#"desc": desc,
#"price": price};
[arrayObjectAdded addObject:newObjectAdded];
}
}
} else {
NSLog(#"Annulla");
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
[_scannerSession resume];
}
- (void)viewDidLoad
{
[super viewDidLoad];
arrayObjectAdded = [[NSMutableArray alloc]init];
CALayer *videoPreviewLayer = [self.videoPreview layer];
[videoPreviewLayer setMasksToBounds:YES];
CALayer *captureLayer = [_scannerSession previewLayer];
[captureLayer setFrame:[self.videoPreview bounds]];
[videoPreviewLayer insertSublayer:captureLayer below:[[videoPreviewLayer sublayers] objectAtIndex:0]];
reader = [[XmlReader alloc]init];
[reader parseXml];
[_scannerSession startCapture];
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
}
- (void)cleanReportArray {
[arrayObjectAdded removeAllObjects];
}
- (void)dealloc {
[_scannerSession stopCapture];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)stopScanner:(id)sender {
ReportViewController *reportVC = [[ReportViewController alloc]initWithNibName:#"ReportViewController" bundle:nil];
reportVC.reportArray = arrayObjectAdded;
[reportVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:reportVC animated:YES completion:nil];
}
#end
To recognize picture I'm using this AR SDK. I hope you can help me to understand where's my issue
Your problem is that in viewDidLoad you have the code:
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
this is the last thing you do in that method. So the instance of PaymentViewController that you create and set the delegate on is immediately destroyed (by ARC).
You need to modify your code so that you call setDelegate: on the actual instance of PaymentViewController that is presented on screen as this is the instance that needs to use the delegate (it receives the callback from the alert view).
I am trying to implement a sign up process with a parse backend. I have a validation method called processFieldEntries and once the done button gets enabled, I try to trigger the segue that I setup modally from my view controller(not from the done button) from view did appear method but neither the validation method gets called nor the segue gets triggered. I setup some debug and logging breakpoints for debugging but, I couldn't go any further apart from the fact that it does not see the view did load. I also tried setting up the segue from the done button. When I did that, the segue gets triggered, not from the code but from storyboard my storyboard here. If someone can help me to figure out how to call processfieldentriees along with the segue, I would really appreciate. Thank you.
NewUserSignUpViewController.h
#import <UIKit/UIKit.h>
#import "ProfileViewController.h"
#interface NewUserSignUpViewController : UIViewController<UITextFieldDelegate>
#property (strong, nonatomic) IBOutlet UIBarButtonItem *barButtonItem;
#property (strong, nonatomic) IBOutlet UITextField *usernameField;
#property (strong, nonatomic) IBOutlet UITextField *passwordField;
#property (strong, nonatomic) IBOutlet UITextField *repeatPasswordField;
- (IBAction)doneEvent:(id)sender;
- (IBAction)cancelEvent:(id)sender;
#end
NewUserSignUpViewController.m
#import "NewUserSignUpViewController.h"
#import "ProfileViewController.h"
#import <Parse/Parse.h>
#import "ActivityView.h"
#interface NewUserSignUpViewController ()
-(void)processFieldEntries;
- (void)textInputChanged:(NSNotification *)note;
- (BOOL)shouldEnableDoneButton;
#end
#implementation NewUserSignUpViewController
#synthesize barButtonItem = _doneButtonInTheBar;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(textInputChanged:) name:UITextFieldTextDidChangeNotification object:_usernameField];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(textInputChanged:) name:UITextFieldTextDidChangeNotification object:_passwordField];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(textInputChanged:) name:UITextFieldTextDidChangeNotification object:_repeatPasswordField];
}
-(void)viewDidAppear:(BOOL)animated
{
[_usernameField becomeFirstResponder];
[super viewDidAppear:animated];
//perform the segue
if (_doneButtonInTheBar.enabled == YES) {
[self performSegueWithIdentifier:#"segueToProfileView" sender:self];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
}
#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{ textField.delegate = self;
if (textField == _usernameField) {[_usernameField becomeFirstResponder];}
if (textField == _passwordField){[_passwordField becomeFirstResponder];}
if (textField == _repeatPasswordField)
{
[_repeatPasswordField becomeFirstResponder];
[self processFieldEntries];
}
return YES;
}
-(BOOL)shouldEnableDoneButton
{
BOOL enableDoneButton = NO;
if (_usernameField.text != nil && _usernameField.text.length != 0 &&_passwordField.text != nil &&
_passwordField.text.length !=0 && _repeatPasswordField.text != nil &&
_repeatPasswordField.text.length != 0) {
enableDoneButton = YES;
[self processFieldEntries];
}
return enableDoneButton;
}
-(void)textInputChanged:(NSNotification *)note
{
_doneButtonInTheBar.enabled = [ self shouldEnableDoneButton];
}
- (IBAction)doneEvent:(id)sender {
[_usernameField resignFirstResponder];
[_passwordField resignFirstResponder];
[_repeatPasswordField resignFirstResponder];
NSLog(#"processfieldentries");
[self processFieldEntries];
}
- (IBAction)cancelEvent:(id)sender {
[self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)processFieldEntries
{
// Check that we have a non-zero username and passwords.
// Compare password and passwordAgain for equality
// Throw up a dialog that tells them what they did wrong if they did it wrong.
NSString *username = _usernameField.text;
NSString *password = _passwordField.text;
NSString *passwordAgain = _repeatPasswordField.text;
NSString *errorText = #"Please ";
NSString *usernameBlankText = #"enter a username";
NSString *passwordBlankText = #"enter a password";
NSString *joinText = #", and ";
NSString *passwordMismatchText = #"enter the same password twice";
BOOL textError = NO;
// Messaging nil will return 0, so these checks implicitly check for nil text.
if (username.length == 0 || password.length == 0 || passwordAgain.length == 0) {
textError = YES;
//setting the keyboard for th first missing output
if (passwordAgain.length == 0) {
[_repeatPasswordField becomeFirstResponder];
}
if (password.length == 0) {
[_passwordField becomeFirstResponder];
}
if (username.length == 0) {
[_usernameField becomeFirstResponder];
}
if (username.length == 0) {
errorText = [errorText stringByAppendingString:usernameBlankText];
}
if (password.length == 0 || passwordAgain.length == 0) {
if (username.length == 0) { // We need some joining text in the error:
errorText = [errorText stringByAppendingString:joinText];
}
errorText = [errorText stringByAppendingString:passwordBlankText];
}
}else if ([password compare:passwordAgain] != NSOrderedSame)
{errorText = [errorText stringByAppendingString:passwordMismatchText];
[_passwordField becomeFirstResponder];}
if (textError) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:errorText message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alertView show];
return;
// Everything looks good; try to log in.
// Disable the done button for now.
_doneButtonInTheBar.enabled = NO;
ActivityView *activityView = [[ActivityView alloc]initWithFrame:CGRectMake(0.f, 0.f, self.view.frame.size.width, self.view.frame.size.height)];
UILabel *label = activityView.label;
label.text = #"signing up";
label.font = [UIFont boldSystemFontOfSize:20.0f];
[activityView.activityIndicator startAnimating];
[activityView layoutSubviews];
[self.view addSubview:activityView];
// Call into an object somewhere that has code for setting up a user.
// The app delegate cares about this, but so do a lot of other objects.
// For now, do this inline.
NSLog(#"does it reach here");
PFUser *user = [PFUser user];
user.username = username;
user.password = password;
[user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[[error userInfo] objectForKey:#"error"] message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alertView show];
_doneButtonInTheBar.enabled = [self shouldEnableDoneButton];
[activityView.activityIndicator stopAnimating];
[activityView removeFromSuperview];
// Bring the keyboard back up, because they'll probably need to change something.
[_usernameField becomeFirstResponder];
return;
}
// Success!
[activityView.activityIndicator stopAnimating];
[activityView removeFromSuperview];
}];
}
}
#end
You could try not to use performSegueWithIdentifier inside viewDidAppear (performSegue actually take you to the other ViewController). Instead you could call it from an IBAction method connected to the done button, after calling in the same method processFieldEntries. I hope this can help you :)
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;
}
I have project very simply as Unity projects, and I want add a new function - sending for email application screenshot,
I try many ways to do that, but I am neebie in IOS and need your help :(
This version is working without errors, but after click button I didnt see email form
code is very short and simple - I hope someone has help me :(((
SampleViewsAppDelegate.h
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <MapKit/MKMapView.h>
#import <MessageUI/MessageUI.h>
#import "tiDFusionMobile.h"
#interface SampleViewsAppDelegate : NSObject <UIApplicationDelegate,MFMailComposeViewControllerDelegate> {
///Application Window
UIWindow *mWindow;
UIViewController *rootViewController;
///Application views
UIView *mRender;
tiComponent* mPlayer;
}
///IBOutlet properties
#property (nonatomic, retain) IBOutlet UIWindow *mWindow;
#property (nonatomic, retain) IBOutlet UIViewController *rootViewController;
#property (nonatomic, retain) IBOutlet UIView *mRender;
- (IBAction)openMailBtn:(id)sender;
- (void)start;
- (void)stop;
#end
file mm
#import "SampleViewsAppDelegate.h"
#implementation SampleViewsAppDelegate
#synthesize mWindow;
#synthesize mRender;
#synthesize rootViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
// allocate the Component
mPlayer = [tiComponent alloc];
// set correct renderer
[mPlayer setRendererType:[tiComponent TI_RENDERER_GLES2]];
// initialze
[mPlayer initialize:mRender];
// start scenario
[self start];
return YES;
}
- (void)dealloc
{
[self stop];
//If the player is still instanciated, it is terminated and released
if (mPlayer)
{
[mPlayer terminate];
[mPlayer release];
mPlayer = nil;
}
[mRender release];
[mWindow release];
[super dealloc];
}
- (IBAction)openMailBtn:(id)sender {
rootViewController = (UIViewController*)
[(SampleViewsAppDelegate*)[[UIApplication sharedApplication] delegate] rootViewController];
if ([MFMailComposeViewController canSendMail]) {
// compose
MFMailComposeViewController* mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
//format message
NSArray *recipientsArray = [[NSArray alloc] initWithObjects:#"test#aaaa.com", nil];
[mail setToRecipients:recipientsArray];
NSString *emailBody = #"DSDSDSDS";
[mail setSubject:[NSString stringWithFormat:#"AAAAAA"]];
//UIImage *myImage = [UIImage imageNamed:#"mobiletuts-logo.png"];
//NSData *imageData = UIImagePNGRepresentation(myImage);
//[mail addAttachmentData:imageData mimeType:#"image/png" fileName:#"mobiletutsImage"];
[mail setMessageBody:emailBody isHTML:YES];
//send
//if (controller)
[rootViewController presentModalViewController:mail animated:YES];
[mail 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 dismissViewControllerAnimated:YES complete:nil];
}
- (void)start
{
if (mPlayer != nil) {
BOOL isLoaded = [mPlayer loadScenario:#"Scenario/SampleViews_GLES1/project.dpd"];
if (isLoaded) {
[mPlayer playScenario];
}
}
}
- (void)stop
{
if (mPlayer && ![mPlayer isScenarioPaused]) {
[mPlayer pauseScenario];
}
}
#end
I GUESS YOU ARE NOT IMPORTING FRAMEWORK
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#interface MailClassViewController : UIViewController<MFMailComposeViewControllerDelegate>
And then the code to present the email screen:
- (IBAction)openMailBtn:(id)sender {
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
mailCont.mailComposeDelegate = self;
[mailCont setSubject:#"Your email"];
[mailCont setMessageBody:[#"Your body for this message is " stringByAppendingString:#" this is awesome"] isHTML:NO];
NSString *file = [documentsDirectory stringByAppendingPathComponent:#"MaintenanceRequest.pdf"];
//IF YOU DONT WANT TO ATTACH FILE THEN COMMENT IT
NSData *data=[NSData dataWithContentsOfFile:file];
[mailViewController addAttachmentData:data mimeType:#"application/pdf" fileName:#"MaintenanceRequest.pdf"];
[self presentViewController:mailCont animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
//handle any error
[controller dismissViewControllerAnimated:YES completion:nil];
}