I am tryin to pass the user login emial to other view controllers. It is going from a UITextField to a UILabel but it display null when I log in a user. I want it to display the email name in the UILabel field. Any help? here are my files.
vc1.h
#import <UIKit/UIKit.h>
#interface loginUserViewController : UIViewController
#property (nonatomic, strong) IBOutlet UITextField *email;
#property (nonatomic, retain) IBOutlet UITextField *password;
#property (nonatomic, retain) IBOutlet UIButton *login;
#property (nonatomic,retain) IBOutlet UIButton *registerBtn;
-(IBAction)loginUser:(id)sender;
#end
vc2.h
#import <UIKit/UIKit.h>
#import "loginUserViewController.h"
#interface Home : UIViewController
#property (weak, nonatomic) IBOutlet NSString *getEmail;
#property (weak, nonatomic) IBOutlet UILabel *username;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *Nav;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *logout;
-(IBAction)logout:(id)sender;
-(IBAction)bandHome:(id)sender;
#end
vc2.m
import "Home.h"
#import "loginUserViewController.h"
#interface Home ()
#end
#implementation Home
#synthesize getEmail,username, band1, band2, band3;
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
// loginUserViewController *object = [[loginUserViewController alloc]init];
// NSString *string = [[NSString alloc] initWithFormat:#"%#", object.email.text];
username.text = getEmail;
}
vc1.m
#import "loginUserViewController.h"
#import "Home.h"
#import "createBandViewController.h"
#interface loginUserViewController ()
#end
#implementation loginUserViewController
#synthesize email, password;
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidload
{
[super viewDidLoad];
}
-(IBAction)loginUser:(id)sender {
if ([email.text isEqualToString:#""] || [password.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return;
}
NSMutableString *strURL = [[NSMutableString alloc] initWithFormat:#"Pretend reference/login2.php?email=%#&password=%#", email.text, password.text ];
[strURL setString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSMutableString *strResult = [[NSMutableString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"logging in");
if ([strResult isEqualToString:#"1"])
{
NSLog(#"Logged in!");
[self performSegueWithIdentifier:#"login" sender:self];
Home *VC;
VC = [self.storyboard instantiateViewControllerWithIdentifier:#"Home"];
[self.navigationController pushViewController:VC animated:YES];
VC.getEmail = self.email.text;
}else
{
// invalid information
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Invalide Information" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
//email.text = #"";
password.text = #"";
}
-(void)WillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
// Dismisses keyboard by clicking out and hitting return key.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *) textField {
[textField resignFirstResponder];
return YES;
}
#end
vc2.h
#property (weak, nonatomic) IBOutlet NSString *getEmail;
vc2.m
#synthesize getEmail;
-(void)viewDidLoad
{
[super viewDidLoad];
username.text = getEmail;
}
vc1.m
-(IBAction)loginUser:(id)sender {
if ([email.text isEqualToString:#""] || [password.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return;
}
else
{
vc2 *VC;
VC = [self.storyboard instantiateViewControllerWithIdentifier:#"vc2Identifier"];
[self.navigationController pushViewController:VC animated:YES];
VC.getEmail = self.email.text
}
}
You don't need to alloc and init the view controller where you have to get the data , but you have to pass the data from vc1 to vc2 and use the variable of vc2 in vc1 , And what your were doing was using the vc1 value in vc2 . And you were allocating the LoginViewController , and in viewDidUnload method , you have set email textfield as nil . that is why you were getting nil value in vc2
Related
so I'm trying to get a variable containing the name of a PDF file I wish to open in a UIweb View to show up in a label. I first identify the global variable in a seperate class here:
header:
#import <Foundation/Foundation.h>
extern NSString *PDFNameString;
extern NSString *PDFActualName;
#interface GlobalVars : NSObject
{
}
#property (nonatomic, strong) NSString *PDFActualName;
#property (nonatomic, strong) NSString *PDFNameString;
#end
.m:
#import "GlobalVars.h"
NSString *PDFNameString;
NSString *PDFActualName; //the name of the PDF file
#implementation GlobalVars
{
}
#end
then I have the menu where I have an alert dialog featuring a text field so that the user can input the PDF name:
.h
#import <Foundation/Foundation.h>
#import "GlobalVars.h"
#interface TitleViewController : UIViewController{
NSFileManager *FM1;
}
#property (retain, nonatomic) IBOutlet UIBarButtonItem *OpenPDF;
#property (retain, nonatomic) IBOutlet UIBarButtonItem *ViewPDF;
-(void)OpeningPDF;
-(void)alertView;
#end
.m
#import "TitleViewController.h"
#interface TitleViewController ()
#end
#implementation TitleViewController
UIAlertView * alert;
UITextField *textField;
int StopTheAlerts = 0;
- (void)viewDidLoad
{
[super viewDidLoad];
FM1 = [NSFileManager defaultManager];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)ButtonClicked:(id)sender {
self.OpeningPDF;
}
- (void)dealloc {
[_OpenPDF release];
[_ViewPDF release];
[super dealloc];
}
- (void)OpeningPDF
{
StopTheAlerts = 0;
alert = [[UIAlertView alloc]
initWithTitle:#"Please enter a valid PDF name below:"
message:#"(Please add .PDF on the end!) \n \n"
delegate:self cancelButtonTitle:#"Cancel"
otherButtonTitles:#"ok", nil];
textField = [[UITextField alloc] init];
[textField setBackgroundColor:[UIColor whiteColor]];
textField.delegate = nil;
textField.borderStyle = UITextBorderStyleLine;
textField.frame = CGRectMake(15, 90, 255, 30);
textField.placeholder = #"PDF name";
textField.keyboardAppearance = UIKeyboardAppearanceAlert; //set up an alert box with a text field
[textField becomeFirstResponder];
[alert addSubview:textField];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
PDFNameString = textField.text; //set the PDF name variable to the name entered
PDFActualName = textField.text;
NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentDir = [Paths objectAtIndex:0];
NSString *TempFilePath = PDFNameString;
PDFNameString = [DocumentDir stringByAppendingPathComponent:TempFilePath];
if([FM1 fileExistsAtPath: PDFNameString]){
_ViewPDF.enabled = true;
}
else {
while(StopTheAlerts <= 0){
UIAlertView *ErrorAlert = [[UIAlertView alloc]
initWithTitle:#"This file dosn't exist!"
message:#"Please reenter the file name!"
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[ErrorAlert show];
[ErrorAlert release];
StopTheAlerts = 1;
}
}
}
#end
This part all works fine, however, when I switch over the the view that contains the UIWebView to actually view the PDF (I've removed that in this part of the code) it has the old "message sent to deallocated instance 0xdb8fca0" error when I try to assign my global variable to the label containing the PDF name, this error also occurs when trying to get the UIWebView to read the PDF using the other global variable.
.h
#import <UIKit/UIKit.h>
#import "GlobalVars.h"
#interface ViewController : UIViewController
#property (retain, nonatomic) IBOutlet UILabel *PDFNameL;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_PDFNameL.text = PDFActualName;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_PDFNameL release];
[super dealloc];
}
#end
If anyone knows a solution to the problem I would be very happy
thanks
I'm pretty new to objective-c and need some tips for my challenge.
I have 2 view controllers and need to show xml data retrieved from FirstViewController to the TermsViewController.
I'm successful getting user input and retrieve xml objects I need.
But don't know how to show the user name in the TermsViewController.m
Since data is downloaded async, can't figure out how to implement this for IOS 6.
Thanks in advance.
FirstViewController.h
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIButton *accessButton;
#property (weak, nonatomic) IBOutlet UITextField *codeField;
#property (weak, nonatomic) NSString *codeUser;
#property (strong, nonatomic) NSString *nameUser;
#property (strong, nonatomic) NSDictionary *xmlDictionary;
#end
TermsViewController.h
#import <UIKit/UIKit.h>
#interface TermsViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *nameLabel;
#property (strong, nonatomic) NSString *nameUserTerms;
#end
FirstViewController.m
#import "FirstViewController.h"
#import "TermsViewController.h"
#import "XMLReader.h"
#interface FirstViewController ()
#property (nonatomic, strong) NSMutableURLRequest *postRequest;
#property NSUInteger responseStatusCode;
#property (nonatomic, strong) NSString *theXML;
#end
#implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)accessButton:(UIButton *)sender {
self.codeUser = self.codeField.text;
NSString *xmlCode = [NSString stringWithFormat:
#"<?xml version='1.0' encoding='utf-8'?>\n"
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
"<soap:Body>\n"
"<GetInterview xmlns='http://www.url.com/url.JCV'>\n"
"<Codigo>"
"%#"
"</Codigo>\n"
"</GetInterview>\n"
"</soap:Body>\n"
"</soap:Envelope>", self.codeUser];
NSLog(#"User code is: %#", self.codeUser);
NSLog(#"XML is: %#", xmlCode);
self.postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.url.com/url.JCV/web.url.asmx"]];
[self.postRequest setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[self.postRequest setHTTPMethod:#"POST"];
[self.postRequest setHTTPBody:[NSMutableData dataWithBytes:[xmlCode UTF8String] length:strlen([xmlCode UTF8String])]];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:self.postRequest delegate:self];
if (conn) {
NSLog(#"Connected to: %#", conn);
} else {
NSLog(#"Connection Error");
}
[self.codeField resignFirstResponder];
}
FirstViewController.m connectionDidFinishLoading method
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
if (self.responseStatusCode == 200) {
NSLog(#"Succeeded! Received %lu bytes of data",[self.theXML length]);
// Parse the XML into a dictionary
NSError *parseError = nil;
self.xmlDictionary = [XMLReader dictionaryForXMLString:self.theXML options:XMLReaderOptionsProcessNamespaces error:&parseError];
NSLog(#"%#", self.xmlDictionary);
//name of the candidate
self.nameUser = [[[[[[[self.xmlDictionary objectForKey:#"Envelope"] objectForKey:#"Body"] objectForKey:#"GetInterviewResponse"] objectForKey:#"GetInterviewResult"] objectForKey:#"Obj"] objectForKey:#"ProfissionalName"] objectForKey:#"text"];
NSLog(#"User name is: %#", self.nameUser);
TermsViewController *nv = [[TermsViewController alloc] init];
nv.nameUserTerms = self.nameUser;
//check
NSLog(#"User name stored: %#", nv.nameUserTerms);
[self performSegueWithIdentifier:#"goToTerms" sender:self];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"bla bla."
delegate:self
cancelButtonTitle:#"Try again"
otherButtonTitles:nil];
[alert show];
}
TermsViewController.m
#import "TermsViewController.h"
#interface TermsViewController ()
#end
#implementation TermsViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.nameLabel.text = self.nameUserTerms;
//this check is returning NULL
NSLog(#"User name: %#", self.nameUserTerms);
}
#end
You should use prepareForSegue to exchange data between controllers.
Remove these lines from your code:
TermsViewController *nv = [[TermsViewController alloc] init];
nv.nameUserTerms = self.nameUser;
And put them in a method like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"goToTerms"]) {
TermsViewController *nv = segue.destinationViewController;
nv.nameUserTerms = self.nameUser;
}
}
I have taken an NSString from one class to another
I have a quiz view controller where a user enters a question in a UITextView and then they press next to go to the select friends view controller where they select a user and then send the question over parse.com
quiz.h
#property (nonatomic,strong) IBOutlet UITextView *textField;
#property (nonatomic, strong) NSString *text;
quiz.m
- (IBAction)next:(id)sender {
NSString *text = self.textField.text;
if ([text length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Enter some text"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
sfvc.string = text;
}
}
selectfriendsviewcontroller.h
#property (nonatomic, retain) NSString *string;
selectfriendsviewcontroller.m
#synthezise string;
- (void)viewDidLoad {
[super viewDidLoad];
quizViewController *qvc = [[quizViewController alloc] init];
qvc.text = string;
UITextView *textfield = [[UITextView alloc] init];
string = textfield.text;
}
why does the string show null?? in the quiz.m when i press next the string passes as null, any ideas as to how i can fix?
In quizViewController under next button action
- (IBAction)next:(id)sender {
if ([text length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Enter some text"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
sfvc.string = self.textField.text;
}
}
Then in selectFriendsViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"string %#",self.string);
}
Also check if the outlet of textView is connected to UITextView or not. If not then connect it. And selectFriendsViewController.h , create property #property (nonatomic, strong) NSString *string;
Hope it helps you.
selectfriendsviewcontroller.m
you can access the value of the string from the string property (by the way avoid generic names like string ) also if you use Xcode > 4.4 you can skip #synthezise
in selectfriendsviewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"%#",self.string);
}
I have created 2 text Fields (Username and Phone number) when I executed my code, only text1(username) is getting executed. i got alert view, in the same way, i tried to give alert view that is text2(phone number) it must allow numeric numbers,
but in my code unable execute second if statement-text2 (phone number)
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
{
__weak IBOutlet UITextField *text1;
__weak IBOutlet UITextField *text2;
IBOutlet UIAlertView *alert;
}
#property (weak, nonatomic) IBOutlet UITextField *text1;
#property (weak, nonatomic) IBOutlet UITextField *text2;
#property (strong, nonatomic) IBOutlet UIAlertView *alert;
#end
.M
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
{
UIAlertView *prompt;
}
#synthesize text1;
#synthesize alert;
#synthesize text2;
- (void)viewDidLoad
{
[super viewDidLoad];
text1.delegate = self;
text2.delegate=self;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==text1)
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"only number allowed" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
return YES;
}
if (textField==text2)
{
NSLog(#"GOOD day");
NSCharacterSet *myCharSet1 = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];
for (int i = 0; i < [string length]; i++)
{
unichar c1 = [string characterAtIndex:i];
if (![myCharSet1 characterIsMember:c1])
{
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"number not allowed" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
}
return YES;
}
#end
You have not set delegate for second textfield. Set delegate of text2 same as text1 as below
- (void)viewDidLoad
{
[super viewDidLoad];
text1.delegate = self;
text2.delegate = self;
}
And for compare UITextField you should use isEqual: instead of = operator. Hence is should be like
if ([textField isEqual:text1]){
.......
Your code here
.......
}
if ([textField isEqual:text2]){
.......
Your code here
.......
}
Change your keyboard type as UIKeyboardTypePhonePad for your phoneTextFeild
phoneTextFeild.keyboardType=UIKeyboardTypePhonePad;
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).