I am using XCode v.4.6 and I am trying to make an app that uses a QR Code scanner. I have followed a tutorial on this page ( http://iphonenativeapp.blogspot.com/2011/07/qr-code-readerscanner-for-iphone-app-in.html ) and have copied and pasted this code:
#import "QRscannerFirstViewController.h"
#interface QRscannerFirstViewController ()
#end
#implementation QRscannerFirstViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"First", #"First");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#import "QRscannerFirstViewController.h"
#end
#implementation QRscannerViewController
#synthesize imgPicker,resultTextView;
-(IBAction)StartScan:(id) sender{
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.readerView.torchMode = 0;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
// EXAMPLE: disable rarely used I2/5 to improve performance
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
// present and release the controller
[self presentModalViewController: reader
animated: YES];
resultTextView.hidden=NO;
}
- (void) readerControllerDidFailToRead: (ZBarReaderController*) reader
withRetry: (BOOL) retry{
NSLog(#"the image picker failing to read");
}
- (void) imagePickerController: (UIImagePickerController*) reader didFinishPickingMediaWithInfo: (NSDictionary*) info
{
NSLog(#"the image picker is calling successfully %#",info);
// ADD: get the decode results
id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
NSString *hiddenData;
for(symbol in results)
hiddenData=[NSString stringWithString:symbol.data];
NSLog(#"the symbols is the following %#",symbol.data);
// EXAMPLE: just grab the first barcode
// break;
// EXAMPLE: do something useful with the barcode data
//resultText.text = symbol.data;
resultTextView.text=symbol.data;
NSLog(#"BARCODE= %#",symbol.data);
NSUserDefaults *storeData=[NSUserDefaults standardUserDefaults];
[storeData setObject:hiddenData forKey:#"CONSUMERID"];
NSLog(#"SYMBOL : %#",hiddenData);
resultTextView.text=hiddenData;
[reader dismissModalViewControllerAnimated: NO];
}
#end
into my .m file. When I put this code ino the editor, I get a warning saying how this
[reader dismissModalViewControllerAnimated: NO];
and this
[self presentModalViewController: reader
animated: YES];
has been decapricated in IOS 6.0.
When I run my application and press a button that starts the QR Scanner, my application quits and it gives me the
Thread 1: signal SIGABRT
error and highlights
return UIApplicationMain(argc, argv, nil, NSStringFromClass([QRscannerAppDelegate class]));
What is recommended for replacing this and how should I fix this error?
Here you go
[self presentViewController:reader animated:YES completion:Nil];
[reader dismissViewControllerAnimated:NO completion:Nil];
Use [self presentViewController:reader animated:YES completion:nil]; and [reader dismissViewControllerAnimated:NO completion:nil];
Related
I am trying to integrate SkyDrive in my iOS application and the following is the code where I have written the login authentication code. The client ID provided here is the one assigned for the application at the developer site. But the authentication always fails. Any idea what is the error ?
static NSString * const CLIENT_ID = #"00000000XXXXXXXXX";
#implementation PSMainViewController
#synthesize appLogo;
#synthesize userInfoLabel;
#synthesize signInButton;
#synthesize viewPhotosButton;
#synthesize userImage;
#synthesize liveClient;
#synthesize currentModal;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
_scopes = [NSArray arrayWithObjects:
#"wl.signin",
#"wl.basic",
#"wl.skydrive",
#"wl.offline_access", nil];
liveClient = [[LiveConnectClient alloc] initWithClientId:CLIENT_ID
scopes:_scopes
delegate:self];
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.appLogo.image = [UIImage imageNamed:#"skydrive.jpeg"];
[self updateUI];
}
- (void)viewDidUnload
{
[self setAppLogo:nil];
[self setUserInfoLabel:nil];
[self setUserImage:nil];
[self setSignInButton:nil];
[self setViewPhotosButton:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)signinButtonClicked:(id)sender {
if (self.liveClient.session == nil)
{
[self.liveClient login:self
scopes:_scopes
delegate:self];
}
else
{
[self.liveClient logoutWithDelegate:self
userState:#"logout"];
}
}
- (IBAction)viewPhotoButtonClicked:(id)sender {
// Create a Navigation controller
PSSkyPhotoViewer *aPhotoViewer = [[PSSkyPhotoViewer alloc] initWithNibName:#"PSSkyPhotoViewer" bundle:nil];
aPhotoViewer.parentVC = self;
self.currentModal = [[UINavigationController alloc] initWithRootViewController:aPhotoViewer];
[self presentModalViewController:self.currentModal animated:YES];
}
- (void) modalCompleted:(id)sender
{
[self dismissModalViewControllerAnimated:YES];
self.currentModal = nil;
}
#pragma mark LiveAuthDelegate
- (void) updateUI {
LiveConnectSession *session = self.liveClient.session;
if (session == nil) {
[self.signInButton setTitle:#"Sign in" forState:UIControlStateNormal];
self.viewPhotosButton.hidden = YES;
self.userInfoLabel.text = #"Sign in with a Microsoft account before you can view your SkyDrive photos.";
self.userImage.image = nil;
}
else {
[self.signInButton setTitle:#"Sign out" forState:UIControlStateNormal];
self.viewPhotosButton.hidden = NO;
self.userInfoLabel.text = #"";
[self.liveClient getWithPath:#"me" delegate:self userState:#"me"];
[self.liveClient getWithPath:#"me/picture" delegate:self userState:#"me-picture"];
}
}
- (void) authCompleted: (LiveConnectSessionStatus) status
session: (LiveConnectSession *) session
userState: (id) userState {
[self updateUI];
}
- (void) authFailed: (NSError *) error
userState: (id)userState {
// Handle error here
}
#pragma mark LiveOperationDelegate
- (void) liveOperationSucceeded:(LiveOperation *)operation {
if ([operation.userState isEqual:#"me"]) {
NSDictionary *result = operation.result;
id name = [result objectForKey:#"name"];
self.userInfoLabel.text = (name != nil)? name : #"";
}
if ([operation.userState isEqual:#"me-picture"]) {
NSString *location = [operation.result objectForKey:#"location"];
if (location) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:location]];
self.userImage.image = [UIImage imageWithData:data];
}
}
}
- (void) liveOperationFailed:(NSError *)error operation:(LiveOperation *)operation
{
// Handle error here.
}
#end
May be you are not providing the redirect url in case of a desktop application.But if it's the mobile application the you have to check the "Mobile or Desktop client app: " as yes in the api settings
hii everyone i am new on this professional site.actually i have a problem in PayPal iOS SDK 2.0.5. This sdk is downloaded from github and now when I tried to logged in paypal then it is not authenticating Can anyone tell that why is this happening and payment is also not transferred in business account from personal account
Thankx
Please help me
here is the link
https://github.com/paypal/PayPal-iOS-SDK/archive/master.zip
#define kPayPalEnvironment PayPalEnvironmentNoNetwork
#interface ZZMainViewController ()
#property(nonatomic, strong, readwrite) IBOutlet UIButton *payNowButton;
#property(nonatomic, strong, readwrite) IBOutlet UIButton *payFutureButton;
#property(nonatomic, strong, readwrite) IBOutlet UIView *successView;
#property(nonatomic, strong, readwrite) PayPalConfiguration *payPalConfig;
#end
#implementation ZZMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"PayPal SDK Demo";
// Set up payPalConfig
_payPalConfig = [[PayPalConfiguration alloc] init];
_payPalConfig.acceptCreditCards = YES;
_payPalConfig.languageOrLocale = #"en";
_payPalConfig.merchantName = #"Awesome Shirts, Inc.";
_payPalConfig.merchantPrivacyPolicyURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/privacy-full"];
_payPalConfig.merchantUserAgreementURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/useragreement-full"];
// Setting the languageOrLocale property is optional.
//
// If you do not set languageOrLocale, then the PayPalPaymentViewController will present
// its user interface according to the device's current language setting.
//
// Setting languageOrLocale to a particular language (e.g., #"es" for Spanish) or
// locale (e.g., #"es_MX" for Mexican Spanish) forces the PayPalPaymentViewController
// to use that language/locale.
//
// For full details, including a list of available languages and locales, see PayPalPaymentViewController.h.
_payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
// Do any additional setup after loading the view, typically from a nib.
self.successView.hidden = YES;
// use default environment, should be Production in real life
self.environment = kPayPalEnvironment;
NSLog(#"PayPal iOS SDK version: %#", [PayPalMobile libraryVersion]);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
// Preconnect to PayPal early
[PayPalMobile preconnectWithEnvironment:self.environment];
}
#pragma mark - Receive Single Payment
- (IBAction)pay {
// Remove our last completed payment, just for demo purposes.
self.resultText = nil;
PayPalPayment *payment = [[PayPalPayment alloc] init];
payment.amount = [[NSDecimalNumber alloc] initWithString:#"9.95"];
payment.currencyCode = #"USD";
payment.shortDescription = #"Hipster t-shirt";
if (!payment.processable) {
// This particular payment will always be processable. If, for
// example, the amount was negative or the shortDescription was
// empty, this payment wouldn't be processable, and you'd want
// to handle that here.
}
// Update payPalConfig re accepting credit cards.
self.payPalConfig.acceptCreditCards = self.acceptCreditCards;
PayPalPaymentViewController *paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment
configuration:self.payPalConfig
delegate:self];
[self presentViewController:paymentViewController animated:YES completion:nil];
}
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
NSLog(#"PayPal Payment Success!");
self.resultText = [completedPayment description];
[self showSuccess];
[self sendCompletedPaymentToServer:completedPayment]; // Payment was processed successfully; send to server for verification and fulfillment
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController {
NSLog(#"PayPal Payment Canceled");
self.resultText = nil;
self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark Proof of payment validation
- (void)sendCompletedPaymentToServer:(PayPalPayment *)completedPayment {
// TODO: Send completedPayment.confirmation to server
NSLog(#"Here is your proof of payment:\n\n%#\n\nSend this to your server for c onfirmation and fulfillment.", completedPayment.confirmation);
}
#pragma mark - Authorize Future Payments
- (IBAction)getUserAuthorization:(id)sender {
PayPalFuturePaymentViewController *futurePaymentViewController = [[PayPalFuturePaymentViewController alloc] initWithConfiguration:self.payPalConfig delegate:self];
[self presentViewController:futurePaymentViewController animated:YES completion:nil];
}
#pragma mark PayPalFuturePaymentDelegate methods
- (void)payPalFuturePaymentViewController:(PayPalFuturePaymentViewController *)futurePaymentViewController didAuthorizeFuturePayment:(NSDictionary *)futurePaymentAuthorization {
NSLog(#"PayPal Future Payment Authorization Success!");
self.resultText = futurePaymentAuthorization[#"code"];
[self showSuccess];
[self sendAuthorizationToServer:futurePaymentAuthorization];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalFuturePaymentDidCancel:(PayPalFuturePaymentViewController *)futurePaymentViewController {
NSLog(#"PayPal Future Payment Authorization Canceled");
self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sendAuthorizationToServer:(NSDictionary *)authorization {
// TODO: Send authorization to server
NSLog(#"Here is your authorization:\n\n%#\n\nSend this to your server to complete future payment setup.", authorization);
}
#pragma mark - Helpers
- (void)showSuccess {
self.successView.hidden = NO;
self.successView.alpha = 1.0f;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelay:2.0];
self.successView.alpha = 0.0f;
[UIView commitAnimations];
}
#pragma mark - Flipside View Controller
- (void)flipsideViewControllerDidFinish:(ZZFlipsideViewController *)controller {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self.flipsidePopoverController dismissPopoverAnimated:YES];
self.flipsidePopoverController = nil;
}
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
self.flipsidePopoverController = nil;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"pushSettings"]) {
[[segue destinationViewController] setDelegate:self];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UIPopoverController *popoverController = [(UIStoryboardPopoverSegue *)segue popoverController];
self.flipsidePopoverController = popoverController;
popoverController.delegate = self;
}
}
}
- (IBAction)togglePopover:(id)sender {
if (self.flipsidePopoverController) {
[self.flipsidePopoverController dismissPopoverAnimated:YES];
self.flipsidePopoverController = nil;
} else {
[self performSegueWithIdentifier:#"showAlternate" sender:sender];
}
}
#end
You are not authenticating the email and password because you have your environment set to PayPalEnvironmentNoNetwork. Setting it to NoNetwork sets it to a "mock" environment and just simulates the actions. You'll need to set the environment to either Live or Sandbox in order to process/authenticate with those environments. The below code is the relevant snippet that you need to look at...
// Set the environment:
// - For live charges, use PayPalEnvironmentProduction (default).
// - To use the PayPal sandbox, use PayPalEnvironmentSandbox.
// - For testing, use PayPalEnvironmentNoNetwork.
#define kPayPalEnvironment PayPalEnvironmentSandbox
My project will save data to parse and while I can pick an image from my library I cannot open the camera. I found a tutorial to do this but it is not compatible with my code. The link to the tutorial is here: Tutorial . I am using .storyboard and the tutorial is .xib, I do not know if this will change anything.
my .m file is here:
#import "NewRecipeViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <Parse/Parse.h>
#import "MBProgressHUD.h"
#interface NewRecipeViewController ()
- (IBAction)save:(id)sender;
- (IBAction)cancel:(id)sender;
#property (weak, nonatomic) IBOutlet UIImageView *recipeImageView;
#property (weak, nonatomic) IBOutlet UITextField *nameTextField;
#property (weak, nonatomic) IBOutlet UITextField *prepTimeTextField;
#property (weak, nonatomic) IBOutlet UITextField *ingredientsTextField;
#end
#implementation NewRecipeViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_nameTextField.delegate = self;
_prepTimeTextField.delegate = self;
_ingredientsTextField.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
[self showPhotoLibary];
}
}
- (void)showPhotoLibary
{
if (([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)) {
return;
}
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// Displays saved pictures from the Camera Roll album.
mediaUI.mediaTypes = #[(NSString*)kUTTypeImage];
// Hides the controls for moving & scaling pictures
mediaUI.allowsEditing = NO;
mediaUI.delegate = self;
[self.navigationController presentModalViewController: mediaUI animated: YES];
}
- (IBAction)save:(id)sender {
// Create PFObject with recipe information
PFObject *recipe = [PFObject objectWithClassName:#"Recipe"];
[recipe setObject:_nameTextField.text forKey:#"name"];
[recipe setObject:_prepTimeTextField.text forKey:#"prepTime"];
NSArray *ingredients = [_ingredientsTextField.text componentsSeparatedByString: #","];
[recipe setObject:ingredients forKey:#"ingredients"];
// Recipe image
NSData *imageData = UIImageJPEGRepresentation(_recipeImageView.image, 0.8);
NSString *filename = [NSString stringWithFormat:#"%#.png", _nameTextField.text];
PFFile *imageFile = [PFFile fileWithName:filename data:imageData];
[recipe setObject:imageFile forKey:#"imageFile"];
// Show progress
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = #"Uploading";
[hud show:YES];
// Upload recipe to Parse
[recipe saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[hud hide:YES];
if (!error) {
// Show success message
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Upload Complete" message:#"Successfully saved the recipe" delegate:Nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
// Notify table view to reload the recipes from Parse cloud
[[NSNotificationCenter defaultCenter] postNotificationName:#"refreshTable" object:self];
// Dismiss the controller
[self dismissViewControllerAnimated:YES completion:nil];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Upload Failure" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}];
}
- (IBAction)cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidUnload {
[self setRecipeImageView:nil];
[self setNameTextField:nil];
[self setPrepTimeTextField:nil];
[self setIngredientsTextField:nil];
[super viewDidUnload];
}
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
UIImage *originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
self.recipeImageView.image = originalImage;
[picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Textfield delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (IBAction)takephoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectphoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
#end
Any help is appreciated.
Take a look at Apple's provided sample project (especially APLViewController.m)
https://developer.apple.com/library/ios/samplecode/PhotoPicker/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010196
You'll see them do the following 4 steps. You are only doing the last half of step one, without first verifying if that source type is even available.
From the UIImagePickerController Class Reference:
To use an image picker controller containing its default controls, perform these steps:
Verify that the device is capable of picking content from the desired source. Do this calling the isSourceTypeAvailable: class method, providing a constant from the “UIImagePickerControllerSourceType” enumeration.
Check which media types are available, for the source type you’re using, by calling the availableMediaTypesForSourceType: class method. This lets you distinguish between a camera that can be used for video recording and one that can be used only for still images.
Tell the image picker controller to adjust the UI according to the media types you want to make available—still images, movies, or both—by setting the mediaTypes property.
Present the user interface. On iPhone or iPod touch, do this modally (full-screen) by calling the presentViewController:animated:completion: method of the currently active view controller, passing your configured image picker controller as the new view controller.
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).
im not able to display the values from this code .plz provide a code to display the mutabledictionay and a
- (void)viewDidLoad{
[super viewDidLoad];
mdict =[[NSMutableDictionary alloc]init];
[mdict setValue:#"abc" forKey:#"def"];
[mdict release];
}
-(void)display{
CFShow(mdict);
}
What about using
-(void)display{
NSLog(#"%#",mdict);
}
Change your method as:
- (void)viewDidLoad{
[super viewDidLoad];
mdict =[[NSMutableDictionary alloc]init];
[mdict setValue:#"abc" forKey:#"def"];
//if you want to display use following statement
[self display];
// [mdict release];//you should not release it here.
}
NOTE: In viewDidLoad you are using [mdict release]; mdict will be released!!!
this should not be in viewDidLoad, put that statement in dealloc.
First You need to create NSMutableDictionary is Public (declare in .h file) because you use it in outside and release its instance in dealloc method
- (void)viewDidLoad{
[super viewDidLoad];
self.mdict =[[NSMutableDictionary alloc]init];
[self.mdict setValue:#"abc" forKey:#"def"];
[self display];
}
-(void)display
{
NSLog(#"%#",[self.mdict objectForKey:#"def"]);
}
and release instance of dictionary in -(void)dealloc method