Saving pictures to parse - ios

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.

Related

didFinishPickingMediaWithInfo is not to work

-(void)cameraAndPhotoAlbums{
self.actionSheet = [[UIActionSheet alloc] initWithTitle:#"title" delegate:self cancelButtonTitle:#"cancel" destructiveButtonTitle:nil otherButtonTitles:#"Photo album",#"camera", nil];
[self.actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePicker animated:YES completion:nil];
} else if(buttonIndex==1) {
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(id)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
}
But at the time of photo album selected photos will only perform the cancel but finish don't perform, tried this item anywhere to write all can't, I again open a project can go agent, a great god save stunned me..
Here is a sample code for you to study:
ViewController.h
#interface ViewController : UIViewController<UIImagePickerControllerDelegate>
{
UIImagePickerController * imagePicker;
}
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)setImageToImageView:(UIButton *)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(#"%#",NSHomeDirectory());
imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Image Picker Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
NSLog(#"Image picked");
self.imageView.image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary)
{
NSData * data = UIImageJPEGRepresentation([info valueForKey:#"UIImagePickerControllerOriginalImage"], 0.5);
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/image.JPEG"];
[data writeToFile:path atomically:true];
}
else
{
UIImageWriteToSavedPhotosAlbum([info valueForKey:#"UIImagePickerControllerOriginalImage"], nil, nil, nil);
}
[self dismissViewControllerAnimated:true completion:nil];
}
- (IBAction)setImageToImageView:(UIButton *)sender
{
if (sender.tag == 101)
{
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
else
{
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[self presentViewController:imagePicker animated:true completion:nil];
}
#end
This code works, tested it on a device.

How do I add an Event Title (from a UI Text View) to a Calendar Event created by my APP?

I've developed an App and my App needs to create an event at device's calendar. I've been trough EventKitProgGuide and studied the SimpleEKDemo.
By simplifying the code from SimpleEKDemo I generated the code shown below that opens an 'calendar's event screen' straight from my app and generates the event properly. I'm OK with that.
Now I need to use the text content of an UITextView as the Event Title!
Could somebody help my with that code?
Thanks,
Marcos
Here's my code:
#.h
#import <EventKitUI/EventKitUI.h>
#import <EventKit/EventKit.h>
#property (nonatomic, strong) EKEventStore *eventStore;
#property (nonatomic, strong) EKEvent *event;
#property (nonatomic, strong) EKCalendar *defaultCalendar;
#property (nonatomic, strong)
IBOutlet UITextView *textView1;
- (IBAction)agendar:(UIButton *)sender;
#.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.eventStore = [[EKEventStore alloc]init];
self.textView1.text = #"hello world!";
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self checkEventStoreAccessForCalendar];
}
- (IBAction)agendar:(UIButton *)sender {
EKEventEditViewController *addController = [[EKEventEditViewController alloc] init];
addController.eventStore = self.eventStore;
addController.editViewDelegate = self;
[self presentViewController:addController animated:YES completion:nil];
self.event = [EKEvent eventWithEventStore:self.eventStore];
// Jeff's suggested code:
self.event.title = self.textView1.text;
// Jeff's SaveEvent Sugestion
NSError *err;
[self.eventStore saveEvent:self.event span:EKSpanThisEvent error:&err];
}
-(void)checkEventStoreAccessForCalendar
{
EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
switch (status)
{
case EKAuthorizationStatusAuthorized: [self accessGrantedForCalendar];
break;
case EKAuthorizationStatusNotDetermined: [self requestCalendarAccess];
break;
case EKAuthorizationStatusDenied:
case EKAuthorizationStatusRestricted:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alerta de Privacidade" message:#"Permissão de acesso ao calendário não concedida."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
break;
default:
break;
}
}
-(void)requestCalendarAccess
{
[self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted)
{
Tela8ViewController * weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf accessGrantedForCalendar];
});
}
}];
}
-(void)accessGrantedForCalendar
{
self.defaultCalendar = self.eventStore.defaultCalendarForNewEvents;
}
- (void)eventEditViewController:(EKEventEditViewController *)controller
didCompleteWithAction:(EKEventEditViewAction)action
{
[self dismissViewControllerAnimated:YES completion:^
{
if (action != EKEventEditViewActionCanceled)
{
dispatch_async(dispatch_get_main_queue(), ^{
});
}
}];
}
There are two ways to create an event with EventKit. Your sample code currently has a mix of both, so you should pick just one!
A: Create an event with certain fields pre-set (in your case, the title), and allow the user to review and save it (or choose to cancel and discard it) with EKEventEditViewController. In this case, your code doesn't need to commit the event - just watch for the delegate response to confirm that it happened.
- (void)createEventWithTitle:(NSString *)title
{
EKEvent *newEvent = [EKEvent eventWithEventStore:self.eventStore];
newEvent.title = title;
EKEventEditViewController *controller = [[EKEventEditViewController alloc] init];
controller.eventStore = self.eventStore;
controller.event = newEvent;
controller.editViewDelegate = self;
[self presentViewController:controller animated:YES completion:nil];
}
// EKEventEditViewController delegate method
- (void)eventEditViewController:(EKEventEditViewController *)controller didCompleteWithAction:(EKEventEditViewAction)action
{
if (action == EKEventEditViewActionSaved) {
// event has been committed
}
// alternatives are EKEventEditViewActionCanceled, EKEventEditViewActionDeleted
[self dismissViewControllerAnimated:YES completion:Nil];
}
B. You can create an event and commit it entirely in your code, if you don't need user involvement. In this case you can use EKEventStore saveEvent: span: error: instead of relying on EKEventEditViewController.
Have you tried something like
self.event.title = self.textView1.text;
?

Clean array by using delegate

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

how to attach camera roll images to mail composer [duplicate]

This question already has answers here:
Attach a photo to an email from my iPhone application
(3 answers)
Closed 9 years ago.
I am having a problem where I'm attaching text and a image to the mail composer my textfields attach fine however when i try to attach an image selected from my camera roll i get a question mark? is it because i have not taken a picture from a ios device, and i am just downloading images from google to test it. Also the application works as follows:
user takes picture and sees it in the UIImageView and then can type his contact details and name and send, or can choose a picture from their camera roll.
.h
#interface xyzViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationBarDelegate> {
IBOutlet UILabel *label;
IBOutlet UITextField *field;
}
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UIButton *TakePhoto;
#property (strong, nonatomic) IBOutlet UIButton *SelectPhoto;
- (IBAction)savedata:(id)sender;
- (IBAction)loaddata:(id)sender;
- (IBAction)dismiss:(id)sender;
- (IBAction)dismiss1:(id)sender;
#property (weak, nonatomic) IBOutlet UITextField *mytextview;
#property (weak, nonatomic) IBOutlet UITextField *mytextview1;
#property (weak, nonatomic) IBOutlet UIImageView *image;
#end
.m file
#interface xyzViewController ()
#end
#implementation xyzViewController
- (IBAction)savedata:(id)sender; {
NSString *savestring = _mytextview.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:#"savedstring"];
[defaults synchronize];
NSString *savestring1 = _mytextview1.text;
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setObject:savestring1 forKey:#"savedstring1"];
[defaults synchronize];
}
- (IBAction)loaddata:(id)sender; {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[_mytextview setText:loadstring];
[label setText:loadstring];
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSString *loadstring1 = [defaults objectForKey:#"savedstring1"];
[_mytextview1 setText:loadstring1];
}
- (IBAction)dismiss:(id)sender {
[sender resignFirstResponder];
}
- (IBAction)dismiss1:(id)sender {
[sender resignFirstResponder];
}
- (IBAction)takePhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectPhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (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.
}
- (IBAction)sendButton:(id)sender {
MFMailComposeViewController *mailContoller = [[MFMailComposeViewController alloc]init];
[mailContoller setMailComposeDelegate:self];
NSString *email = #"avip606#gmail.com";
NSString *email1 = #"avi_sp#hotmail.co.uk";
NSArray *emailArray = [[NSArray alloc]initWithObjects:email, email1, nil];
NSString *message = [#[_mytextview.text, _mytextview1.text] componentsJoinedByString: #"\n"];
[mailContoller setMessageBody:message isHTML:NO];
NSData *data = UIImagePNGRepresentation(_image);
[mailContoller addAttachmentData:data
mimeType:#"image/png"
fileName:#"image.png"];
[mailContoller setToRecipients:emailArray];
[mailContoller setSubject:#"IT WORKS!"];
[self presentViewController:mailContoller animated:YES completion:nil];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self mytextview] resignFirstResponder];
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
to take photo use
- (IBAction)takePhotoCam:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
[self.navigationController presentViewController:imagePicker animated:YES completion:nil];
}
To choose from gallery use
- (IBAction)choosePhotoFromLibrary:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
[self.navigationController presentViewController:imagePicker animated:YES completion:nil];
}
Now use delegate to read that photo and attach in email...
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
filePath = [documentsPath stringByAppendingPathComponent:#"myCameraImage.png"];
NSLog(#"saving data at === %#", filePath);
[pngData writeToFile:filePath atomically:YES]; //Write the file
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
Now in Documents folder, you have image called myCameraImage.png
Now let's say you have button called Send on email. On clicking create IBAction and attach myCameraImage.png to email.
See here, how to attach image to email.

UIImagePickerController disable iPhone 4S face detection (iOS 5.1)

I am currently developing an iPhone app that makes use of a UIImagePickerController with a custom overlay to take photos.
Unfortunately I do not have direct access to an iPhone 4S but several testers have reported that the camera picker is drawing a green border around faces exactly like this: http://cdn.iphonehacks.com/wp-content/uploads/2012/03/camera_faces.jpg
Due to the nature of this app this is not desirable.
A thorough search of the UIImagePickerController docs didn't turn up anything and similarly everything I could find on here relating to face detection was providing instructions in how to use a CIDetector or similar.
How can I disable face detection in my UIImagePickerController?
Here is my initialisation code for the UIImagePickerController:
UIImagePickerController *cameraPicker = [[UIImagePickerController alloc] init];
[cameraPicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[cameraPicker setCameraDevice:UIImagePickerControllerCameraDeviceRear];
if ([UIImagePickerController isFlashAvailableForCameraDevice:cameraPicker.cameraDevice]){
[cameraPicker setCameraFlashMode:UIImagePickerControllerCameraFlashModeOn];
}
[cameraPicker setShowsCameraControls:NO];
[cameraPicker setCameraOverlayView:cameraOverlayView];
cameraPicker.delegate = self;
[self presentModalViewController:cameraPicker animated:YES];
Try This -->
Lets Say We have one UIViewController named as - RecordVideoViewController
Implementation of -- RecordVideoViewController.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import <AssetsLibrary/AssetsLibrary.h>
#interface RecordVideoViewController : UIViewController
- (IBAction)recordAndPlay:(id)sender;
-(BOOL)startCameraControllerFromViewController:(UIViewController*)controllerusingDelegate:
(id)delegate;
-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error
contextInfo(void*)contextInfo;
#end
Implementation of -- RecordVideoViewController.m
- (IBAction)recordAndPlay:(id)sender {
[self startCameraControllerFromViewController:self usingDelegate:self];
}
-(BOOL)startCameraControllerFromViewController:(UIViewController*)controller
usingDelegate:(id )delegate
{
// 1 - Validattions
if (([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ==
NO)
|| (delegate == nil)
|| (controller == nil)) {
return NO;
}
// 2 - Get image picker
UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
// Displays a control that allows the user to choose movie capture
cameraUI.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
// Hides the controls for moving & scaling pictures, or for
// trimming movies. To instead show the controls, use YES.
cameraUI.allowsEditing = NO;
cameraUI.delegate = delegate;
// 3 - Display image picker
[controller presentViewController:cameraUI animated:YES completion:nil];
return YES;
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:
(NSDictionary *)info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
// Handle a movie capture
if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeMovie, 0) ==
kCFCompareEqualTo) {
NSString *moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum(moviePath,
self,#selector(video:didFinishSavingWithError:contextInfo:),nil);
}
}
}
-(void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:
(void*)contextInfo {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Video Saving
Failed"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Video Saved" message:#"Saved To
Photo Album" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Implement This code it, i hope this will help you .
Check out this post. There are some hints here, but still can't find much info outside of Apple's docs on this API.
Proper usage of CIDetectorTracking

Resources