I am using tab bar in my iOS app. When I tap on the scan tab, i invoked the delegate method to start the camera immediately on scan tab. When I start the camera to scan the QR Code and tap on cancel button before scanning, I get the blank view. How to display the view when camera is dismissed
- (void) openCameraScanner
{
ZBarReaderViewController *reader = [[ZBarReaderViewController alloc] init];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
reader.showsZBarControls = YES;
ZBarImageScanner *scanner = reader.scanner;
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
[self presentViewController:reader animated:YES completion:nil];
reader.showsZBarControls = YES;
//reader.cameraOverlayView = [self commonOverlay];
}
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
// ADD: get the decode results
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
//resultsView.text = symbol.data;
NSString *urlString = symbol.data;
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"Query after scan = %#", [url query]);
//Extract id from URL which is there in QR Code --- start
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for(NSString *param in [urlString componentsSeparatedByString:#"&"])
{
NSArray *elements = [param componentsSeparatedByString:#"="];
if([elements count]<2)
continue;
[dictionary setObject:[elements objectAtIndex:1] forKey:[elements objectAtIndex:0]];
NSLog(#"value is == %#", [elements objectAtIndex:1]);
//Extract id from URL which is there in QR Code --- end
if([[elements objectAtIndex:1] intValue])
{
NSUserDefaults *defaultsForAsk = [NSUserDefaults standardUserDefaults];
idToAsk = [NSString stringWithFormat:#"%d",[[elements objectAtIndex:1] intValue]];
[defaultsForAsk setObject:idToAsk forKey:#"IDTOASKVIEW"];
flagToShowView = YES;
listViewCntrl.getFlag = flagToShowView;
[self viewDidLoadForDynamicFields];
}
else if([elements objectAtIndex:1] == [NSNull null])
{
[reader dismissViewControllerAnimated:YES completion:Nil];
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Invalid QR Code scanned" message:#"Please scan Collaborator's QR Code" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[message show];
}
}
image.image =
[info objectForKey: UIImagePickerControllerOriginalImage];
// ADD: dismiss the controller (NB dismiss from the *reader*!)
//[reader dismissViewControllerAnimated:YES completion:nil];
[reader dismissViewControllerAnimated:YES completion:Nil];
}
You can re display the view using -(void)viewWillAppear:(BOOL)animated method of your ViewController class.
Related
I am having an interesting little problem using the uiimagepickercontroller and was wondering if anyone has any insight as to what might be happening. Users can take pictures with the camera or pick from the photo library until the cows come home as many times in a row as they like. My issue lies in allowing users to revert back to the original image that shipped with the app. Here is the flow:
Users go the the tableview which shows a thumbnail of the image.
Users navigate to the detail view which shows a larger view of the image.
Users can tap on the image in the detail view to bring up a custom alertcontroller with options to a) use the camera to take a picture, b) use a picture from their library, or c) revert back to the original image.
Users choose either option 'a' or option 'b' to either take a picture or use a picture from the photo library. IF they IMMEDIATELY change their mind about using one of those choices and want to just go back to using the original image, nothing happens! They can snap another picture or choose another image right away, but cannot revert back to the original image right away.
Reverting back to the original image DOES work perfectly when the app has been closed and then opened again. Sometimes it will work if you navigate around to other views within the app and then come back to the detail view where they just added their own image. By why the delay? I've searched around for two weeks but have not found anything resembling my problem or any solutions that help in any way (like reloading the headerview where image is sitting). Any thoughts?
Also I have figured out how to save the image to iCloud by using the documentation but cannot figure out how to retrieve them so there is no code for that. That is entirely different question. The same thing seems to occur even without that code.
Thanks for taking the time to look at this!
Here is some code:
-(void)bookImageTapped:(UIGestureRecognizer *)gesture
{
URBAlertView *changeImageAlertView = [[URBAlertView alloc] initWithTitle:#"Add A New Book Cover Image" message:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Use Camera", #"Open Gallery", #"Use Original Photo", nil];
[changeImageAlertView setHandlerBlock:^(NSInteger buttonIndex, URBAlertView *alertView) {
[self checkPermission];
if (PHAuthorizationStatusAuthorized)
{
if(buttonIndex == 0)
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else
{
NSLog(#"Camera not available");
[alertView hide];
}
}
else if (buttonIndex == 1)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else if (buttonIndex == 2)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self restoreOriginalPhoto];
}];
[alertView hide];
}
else
{
NSLog(#"button 2 cancel");
[alertView hide];
}
}
}];
[changeImageAlertView show];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_book.largeBookImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_book.largeBookImage = [self scaleImage:_book.largeBookImage toSize:CGSizeMake(120, 168)];
_bookImageView.image = _book.largeBookImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"png record saved after using picker!");
}];
}
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"jpg record saved after using picker!");
}];
}
}
else
{
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
- (UIImage *) scaleImage:(UIImage*)image toSize:(CGSize)newSize
{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
-(void)restoreOriginalPhoto
{
NSLog(#"restore photo called");
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
Here is the headerview with the imageview:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
_headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 26)];
_headerView.backgroundColor = [UIColor colorWithRed:8/255.0 green:46/255.0 blue:46/255.0 alpha:0.8];
if (section == 0)
{
_headerView.backgroundColor = [UIColor whiteColor];
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake((tableView.frame.size.width - 120)/2, 6, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
UITapGestureRecognizer *bookImageTouched = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(bookImageTapped:)];
bookImageTouched.numberOfTapsRequired = 1;
[_bookImageView addGestureRecognizer:bookImageTouched];
_bookImageView.userInteractionEnabled = YES;
[_headerView addSubview:_bookImageView];
}
I finally figured it out! It seems that I was confusing xcode with my property names. The code ended up much simpler in the end.
In didFinishPickingMediaWithInfo I created a UIImage and then set it to the bookImageView.image. Later, when I wanted to be able to update the image back to the original image, then I could call the bundle asset, _book.largeBookImage. Voila! The image was able to update immediately.
The most pertinent code is posted below.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_chosenImage = [[UIImage alloc] init];
_chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_bookImageView.image = _chosenImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_chosenImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else
{
//NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
-(void)restoreOriginalPhoto
{
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
_backgroundImage.image = _book.largeBookImage;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 0)
{
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
_bookImageView.clipsToBounds = YES;
_bookImageView.layer.cornerRadius = 10.0f;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
[self.tableView reloadData];
[self.tableView setContentOffset:CGPointZero animated:NO];
}
Hi I'm new to iOS development. I want to pick a contact from default contacts app. For that i created an application that lets user to pick a contact from the iPhone default contacts app. For iOS 9+ version, I'm using the following snipped.
- (IBAction)btnAction:(id)sender {
CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
contactPicker.delegate = self;
contactPicker.displayedPropertyKeys = (NSArray *)CNContactGivenNameKey;
[self presentViewController:picker animated:YES completion:nil];
}
-(void) contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
NSLog(#"Contact : %#",contact);
}
-(void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
NSLog(#"Cancelled");
}
I also added CNContactPickerDelegate delegate in my uiviewcontroller. When i execute the above code, it opens the contacts app, But when Tap a contact the app becomes blank.
Thanks in advance and can anyone please share your knowledge to use CNContactPickerViewController in Objective-C.
The issue is caused by this code:
contactPicker.displayedPropertyKeys = (NSArray *)CNContactGivenNameKey;
The displayedPropertyKeys expects an NSArray which contains NSString values. In your code, you are trying to type cast an NSString to NSArray and set as the value of this property.
You need to change your code to:
contactPicker.displayedPropertyKeys = #[CNContactGivenNameKey];
#pragma mark - CNContactPickerViewController Delegate method implementation
(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact
{
NSMutableArray *contactNumberArray = [[NSMutableArray alloc]init];
selectedName=[NSString stringWithFormat:#"%#",contact.givenName];
NSLog(#"%#",selectedName);
NSString *tempString = [NSString stringWithFormat:#"name : %# %# %#\n",contact.givenName, contact.familyName, contact.organizationName];
// // 1. (Phone Numbers)
tempString = [NSString stringWithFormat:#"%#phoneNumbers : ",tempString];
// NSArray*phoneNumber = contact.phoneNumbers;
for (CNLabeledValue *phoneNumber in contact.phoneNumbers)
{
CNPhoneNumber *phone = phoneNumber.value;
tempString = [NSString stringWithFormat:#"%#<%#>",tempString,phone.stringValue];
[contactNumberArray addObject:phone];
selectedPhNumber=[[NSString stringWithFormat:#"%#",phone.stringValue] stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"%#",selectedPhNumber);
}
//2. (Emails)
tempString = [NSString stringWithFormat:#"%#\n Email : ",tempString];
for (CNLabeledValue *email in contact.emailAddresses)
{
selectedEmail=[NSString stringWithFormat:#"%#", email.value];
tempString = [NSString stringWithFormat:#"%#<%#>",tempString,email.value];
[contactNumberArray addObject:email];
NSLog(#"%#",selectedEmail);
}
[self sendRefferelDetailsToServer];
}
-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts{
NSLog(#" %#",contacts);
CNContact *contact=[contacts objectAtIndex:0];
NSLog(#"name = %#",contact.givenName);
}
[1]: https://i.stack.imgur.com/9Sp1G.png use above code to for fetch given name from multiple selections,
comment the following line and try again.
//contactPicker.displayedPropertyKeys = (NSArray *)CNContactGivenNameKey;
I am using a custom tableview cell that displays text in chat bubbles and its working fine.
But i want to display images in chat.
For that i am doing belowed steps:
TO choose and upload file:
- (IBAction)btnAttachments:(id)sender{
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.allowsEditing = NO;
self.imagePicker.delegate = self;
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:self.imagePicker animated:YES completion:nil];}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *imgChosen = info[UIImagePickerControllerOriginalImage];
imgChat = imgChosen;
[picker dismissViewControllerAnimated:YES completion:NULL];
// Upload new avatar to Content module
NSData *avatar = [[NSData alloc] initWithData:UIImagePNGRepresentation(imgChat)];
//
//[QBContent TUploadFile:avatar fileName:#"MyAvatar" contentType:#"image/png" isPublic:NO delegate:self];
[QBContent TUploadFile:avatar fileName:#"userChat" contentType:#"image/png" isPublic:YES delegate:self];}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
in Completed with result:
if(result.success && [result isKindOfClass:[QBCFileUploadTaskResult class]])
{
QBCFileUploadTaskResult *res = (QBCFileUploadTaskResult *)result;
NSUInteger uploadedFileID = res.uploadedBlob.ID;
QBChatMessage *message = [[QBChatMessage alloc] init];
message.recipientID = self.opponent.ID;
NSMutableDictionary *msgDict = [[NSMutableDictionary alloc]init];
[msgDict setValue:[NSNumber numberWithInt:uploadedFileID] forKey:#"fileID"];
message.customParameters = msgDict;
[[QBChat instance] sendMessage:message];
}
To download file:
- (void)chatDidReceiveMessageNotification:(NSNotification *)notification{
QBChatMessage *message = notification.userInfo[kMessage];
if(message.customParameters != nil)
{
NSUInteger fileID = [message.customParameters[#"fileID"] integerValue];
// download file by ID
[QBContent TDownloadFileWithBlobID:fileID delegate:self];
}
in completed with result:
if(result.success && [result isKindOfClass:[QBCFileDownloadTaskResult class]])
{
QBCFileDownloadTaskResult *res = (QBCFileDownloadTaskResult *)result;
if ([res file])
{
UIImageView* imageView = [[UIImageView alloc] initWithImage:
[UIImage imageWithData:[res file]]];
[self.messages addObject:imageView];
[self.tblObj reloadData];
}
}
Now, How to display that downloaded image in my chat?
Instruct me about the custom cell which will be used for displaying images.
I want to present a MFMailComposeViewController from a modal view controller. Basically this method works, but it does not work reliably:
-(void)sendMailTapped:(id)sender{
[self resetButtonsStateAfterTapping:sender];
[self dismissPopover];
if (filesize>10) {
[self showAlertForExceededMaximumAttachmentSize];
return;
}
#try {
MFMailComposeViewController *picker =
[[MFMailComposeViewController alloc] init];
if ([MFMailComposeViewController canSendMail]) {
picker.mailComposeDelegate = self;
NSURL *path =[NSURL urlWithPath:[pageInfoDict valueForKey:#"file_name"]
docId:[pageInfoDict valueForKey:#"id_doc"]
encrypted:[[pageInfoDict valueForKey:#"encrypted"]
boolValue]] ;
NSString *fileName = [pageInfoDict valueForKey:#"title"];
if([fileName length] == 0) {
fileName = [path lastPathComponent];
}
if(![fileName hasSuffix:[path pathExtension]]){
fileName=[fileName stringByAppendingFormat:#".%#",[path pathExtension]];
}
[picker setSubject:[#"Send document: " stringByAppendingString:fileName]];
NSArray *ccRecipients = [NSArray arrayWithObjects:
[[CustomisationConfig getAppConfig] getCCMail],nil];
[picker setCcRecipients:ccRecipients];
NSArray *bccRecipients = [NSArray arrayWithObjects:
[[CustomisationConfig getAppConfig] getBCCMail],nil];
[picker setBccRecipients:bccRecipients];
NSData *myData = [path decryptedData];
[picker addAttachmentData:myData
mimeType:fileMIMEType(fileName) fileName:fileName];
NSString *emailBody = [NSString stringWithFormat:
#"\n\nThis file was sent using %#.",
[DCConfiguration getHumanReadableAppName] ];
[picker setMessageBody:emailBody isHTML:NO];
[self presentViewController:picker animated:true completion:^(void){}];
}
}
#catch (NSException *exception) {
NSLog(#"ContextMenuViewController sendMailTapped:%#",exception.description);
}
}
If I restart my iPad and open the app, the picker will be presented only on the second tap on the corresponding button.
If I click again on the button after this, the picker will be presented on first touch everytime and it works perfectly, until I shutdown and restart the iPad.
The following is printed to the console:
Warning: Attempt to present <MFMailComposeViewController: 0x200cbb70> on <ContextMenuViewController: 0x200cd1a0> whose view is not in the window hierarchy!
What is calling the sendMailTapped: method? If its interface builder, you need to change it to IBAction instead of void, and connect them in interface builder.
I am doing one iOS app in which I have to scan the barcodes . I have used ZBarReaderViewController for scanning the barcodes . Sometimes it is giving the result accurately but sometimes it is giving unknown value like this &7&#,Ac9 .My Image is My code is
-(IBAction)scanBarCode:(id)sender
{
reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
reader.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height * [UIScreen mainScreen].scale >= 1136)
[reader.readerView setScanCrop:(CGRect){ { 0.25, 0.08 }, { 0.07, 0.84} }];//.25
else
[reader.readerView setScanCrop:(CGRect){ { 0.23, 0.08 }, { 0.09, 0.84} }];
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];*/
//swetha test
[scanner setSymbology: 0
config: ZBAR_CFG_ENABLE
to: 0];
// Enable EAN 13
[scanner setSymbology: ZBAR_EAN13
config: ZBAR_CFG_ENABLE
to: 1];
// Enable UPC-A
[scanner setSymbology: ZBAR_UPCA
config: ZBAR_CFG_ENABLE
to: 1];
// Enable Code 128
[scanner setSymbology: ZBAR_CODE128
config: ZBAR_CFG_ENABLE
to: 1];
[self presentViewController:reader animated:YES completion:nil];
[reader release];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
serialnumber.text = symbol.data;
// EXAMPLE: do something useful with the barcode image
//resultImage.image =
//[info objectForKey: UIImagePickerControllerOriginalImage];
// ADD: dismiss the controller (NB dismiss from the *reader*!)
barcodeClicked = 0;
[picker dismissViewControllerAnimated:YES completion:nil];
}
Please let me know if I am not clear . Thanks in advance .
My imagepickerControll function is as follows:
- (void) imagePickerController: (UIImagePickerController*)reader didFinishPickingMediaWithInfo: (NSDictionary*) info {
#try {
id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
for(id obj in results) {
ZBarSymbol *symbol = obj;
serialnumber.text = [symbol data];
}
}
#catch (NSException *ex) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"%#",ex]
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
barcodeClicked = 0;
[reader dismissViewControllerAnimated:YES completion:nil];
}
I would strongly recommend using try-catch and going through all the results, since it may interpret 2 different barcodes if they are close by, and parsing the object as ZBarSymbol.