Inconsistency barcode results using ZBarReaderViewController in ios - ios

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.

Related

Can't Revert Back to Original Image After Using UIImagePickerController

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];
}

UIImagePickerController startVideoCapture with native controls?

I'm using Phonegap's implementation to use the video capture and can't seem to get startVideoCapture to work. I'm a novice when it comes to Objective C, so I apologize if I'm off base here. Sounds like startVideoCapture is mainly for custom UI's. Is there something I can do to auto start the video recording (since I'm starting the video interface from another action). Here's a link to the full file:
https://github.com/apache/cordova-plugin-media-capture/blob/master/src/ios/CDVCapture.m
Thanks,
Steve
- (void)captureVideo:(CDVInvokedUrlCommand*)command
{
NSString* callbackId = command.callbackId;
NSDictionary* options = [command.arguments objectAtIndex:0];
NSLog(#"hereeeee");
if ([options isKindOfClass:[NSNull class]]) {
options = [NSDictionary dictionary];
}
// options could contain limit, duration and mode
// taking more than one video (limit) is only supported if provide own controls via cameraOverlayView property
NSNumber* duration = [options objectForKey:#"duration"];
NSString* mediaType = nil;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
// there is a camera, it is available, make sure it can do movies
pickerController = [[CDVImagePicker alloc] init];
NSArray* types = nil;
if ([UIImagePickerController respondsToSelector:#selector(availableMediaTypesForSourceType:)]) {
types = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
// NSLog(#"MediaTypes: %#", [types description]);
if ([types containsObject:(NSString*)kUTTypeMovie]) {
mediaType = (NSString*)kUTTypeMovie;
} else if ([types containsObject:(NSString*)kUTTypeVideo]) {
mediaType = (NSString*)kUTTypeVideo;
}
}
}
if (!mediaType) {
// don't have video camera return error
NSLog(#"Capture.captureVideo: video mode not available.");
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:CAPTURE_NOT_SUPPORTED];
[self.commandDelegate sendPluginResult:result callbackId:callbackId];
pickerController = nil;
} else {
pickerController.delegate = self;
pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
pickerController.allowsEditing = NO;
// iOS 3.0
pickerController.mediaTypes = [NSArray arrayWithObjects:mediaType, nil];
if ([mediaType isEqualToString:(NSString*)kUTTypeMovie]) {
if (duration) {
pickerController.videoMaximumDuration = [duration doubleValue];
}
// NSLog(#"pickerController.videoMaximumDuration = %f", pickerController.videoMaximumDuration);
}
// iOS 4.0
if ([pickerController respondsToSelector:#selector(cameraCaptureMode)]) {
pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
// pickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
// pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
// pickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
}
// CDVImagePicker specific property
pickerController.callbackId = callbackId;
SEL selector = NSSelectorFromString(#"presentViewController:animated:completion:");
if ([self.viewController respondsToSelector:selector]) {
[self.viewController presentViewController:pickerController animated:YES completion:nil];
} else {
// deprecated as of iOS >= 6.0
[self.viewController presentModalViewController:pickerController animated:YES];
}
// Auto start capture
[pickerController startVideoCapture];
}
}
My problem wasn't the use of startVideoRecording, it was when:
[self.viewController presentViewController:pickerController animated:YES completion:^(){
[pickerController startVideoCapture];
}];
Hope this helps someone else.
Thanks,
Steve

Cancel button action in zbar shows blank view

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.

Create universal search textfield (google and url) in iOS 7

How do we create a universal search textfield like in iOS 7 safari. I know how to create a Google search field, but how can I create one textfield which has both Google search and URL search.
Google Searchfield:
-(void)SearchButtonClicked {
NSString *query = [maintext.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSString *urlString = [NSString stringWithFormat:#"%#", query];
// remember to change the view controller class in storyboard
MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"WebView"];
// urlString is a public property on MyWebViewController
webViewController.urlString = urlString;
[self presentViewController:webViewController animated:YES completion:nil];
}
- (IBAction)SearchButton:(id)sender {
NSString *query = [maintext.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSString *urlString = [NSString stringWithFormat:#"http://www.google.com/search?q=%#", query];
// remember to change the view controller class in storyboard
MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"WebView"];
// urlString is a public property on MyWebViewController
webViewController.urlString = urlString;
[self presentViewController:webViewController animated:YES completion:nil];
}
My Webview controller:
#import "MyWebViewController.h"
#import "ViewController.h"
#import <Social/Social.h>
#import "SIAlertView.h"
#import "TTAlertView.h"
#import "ETActivityIndicatorView.h"
#implementation MyWebViewController {
}
#synthesize searchField;
#synthesize webView;
ETActivityIndicatorView * etActivity;
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSURL *url = [NSURL URLWithString:self.urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
-(void)webView:(UIWebView *)webBlog didFailLoadWithError:(NSError *)error{
if ([error code] != -999) {
NSLog(#"Could not load the dumb webPage");
//show error alert, etc.
TTAlertView *alert = [[TTAlertView alloc] initWithTitle:#"Internet Error"
message:#"Searched cannot open the page because your iPhone is not connected to the internet."
delegate:self
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
[etActivity setHidden:YES];
}else{
NSLog(#"Could not load the dumb web page...just might blame user!");
}
}
//Called whenever the view starts loading something
- (void)webViewDidStartLoad:(UIWebView *)webView {
[etActivity startAnimating];
[etActivity setHidden:NO];
}
//Called whenever the view finished loading something
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[etActivity stopAnimating];
[etActivity setHidden:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[webView setDelegate:self];
self.searchField.backgroundColor = [UIColor colorWithRed:255.0/255 green:255.0/255 blue:255.0/255 alpha:1.0f];
self.searchField.layer.cornerRadius = 3.0f;
self.searchField.placeholder = #"Search or enter address";
self.searchField.leftViewMode = UITextFieldViewModeAlways;
UIView* leftView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
self.searchField.leftView = leftView1;
//Setup handling of LEFT and RIGHT swipes
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[[self view] addGestureRecognizer:recognizer];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[[self view] addGestureRecognizer:recognizer];
self.searchField.delegate = self;
//ETActivityIndicatorView
etActivity = [[ETActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 60.0f, 60.0f)];
etActivity.center=self.view.center;
//you can set your custom color for ETActivityIndicatorView
etActivity.color = [UIColor colorWithRed:13.0/255 green:136.0/255 blue:236.0/255 alpha:1.0f];
[self.view addSubview:etActivity];
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
NSLog(#"Swipe Right");
[webView goBack];
}
if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
NSLog(#"Swipe Left");
[webView goForward];
}
}
#pragma mark - RNGridMenuDelegate
- (void)gridMenu:(RNGridMenu *)gridMenu willDismissWithSelectedItem:(RNGridMenuItem *)item atIndex:(NSInteger)itemIndex {
if (itemIndex == 0) {
NSLog(#"Reload");
[self.webView reload];
}
if (itemIndex == 1) {
NSLog(#"Facebook");
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) //check if Facebook Account is linked
{
mySLComposerSheet = [[SLComposeViewController alloc] init]; //initiate the Social Controller
mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; //Tell him with what social plattform to use it, e.g. facebook or twitter
[mySLComposerSheet setInitialText:[NSString stringWithFormat:#""]]; //the message you want to post
[self presentViewController:mySLComposerSheet animated:YES completion:nil];
}
[mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
switch (result) {
case SLComposeViewControllerResultCancelled:
break;
case SLComposeViewControllerResultDone:
break;
default:
break;
} //check if everything worked properly. Give out a message on the state.
}];
}
if (itemIndex == 2) {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:#""];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
if (itemIndex == 3) {
NSLog(#"Home");
MyWebViewController *MainView = [self.storyboard instantiateViewControllerWithIdentifier:#"MainView"];
[self presentViewController:MainView animated:NO completion:nil];
}
}
- (void)showList {
NSInteger numberOfOptions = 4;
NSArray *options = #[
#"Reload",
#"Facebook",
#"Twitter",
#"Home",
];
RNGridMenu *av = [[RNGridMenu alloc] initWithTitles:[options subarrayWithRange:NSMakeRange(0, numberOfOptions)]];
av.delegate = self;
av.itemFont = [UIFont boldSystemFontOfSize:18];
av.itemSize = CGSizeMake(150, 55);
[av showInViewController:self center:CGPointMake(self.view.bounds.size.width/2.f, self.view.bounds.size.height/2.f)];
}
- (IBAction)onShowButton:(id)sender {
[self showList];
}
![enter image description here][1]
Google Chrome assumes the typed text is a URL in these cases:
Text contains no whitespaces (One word):
Starts with a valid and accepted URI scheme (Like http, https, and ftp).
Starts with a forward slash (/).
Ends with a valid TLD (See 1, 2, 3).
Ends with a forward slash (/).
Known hostnames (Like localhost).
Valid IP addresses.
Text contains whitespaces (Multiple words):
Starts with a forward slash (/).
Text contains a question mark (?) and the part before it can be assumed a URL.
In all other cases you can safely assume the typed text is a search term.
This isn't a complete list of rules, but I think it's more than enough for regular usage.
Main reference: Chromium - Omnibox design principles.
Update:
Here are some hints to help you convert the previous rules to a working code (the order is important):
(Rule 3) Replace the part of text that matches this regular expression:
\?.*$
with empty string #"", and then apply other rules.
(Rules 1.1, 1.2, 1.4, 1.5, and 2.1) Match against this regular expression:
^((\/)|((https?|ftp):\S+$)|(\S+\/$)|(localhost$))
(Rule 1.3) You can collect some popular TLDs from the links above and form a one regular expression from them like this:
\S+\.(com|net|org|....)$
(Rule 1.6) Match against this regular expression:
^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9‌​]{2}|2[0-4][0-9]|25[0-5])$
Use this code. This basically checks the text entered into the textfield. If it's a complete url, then it redirects directly to it else the text entered is searched on google.
- (IBAction)SearchButton:(id)sender
{
MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"WebView"];
NSString *urlString = maintext.text;
if([urlString rangeOfString:#"//"].location == NSNotFound)
{
// to resolve a url according to rfc 1808 (the most common form of URL), it must contain '//' in it.
// appending '//' in the url string to check for valid url
urlString = [NSString stringWithFormat:#"//%#", urlString];
}
NSURL *url = [NSURL URLWithString:urlString];
if(url && (url.scheme || url.host) && ([urlString rangeOfString:#"."].location != NSNotFound))
{
// url is valid, it contains domain and host
webViewController.urlString = maintext.text;
}
else
{
NSString *query = [maintext.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSString *urlString = [NSString stringWithFormat:#"http://www.google.com/search?q=%#", query];
// urlString is a public property on MyWebViewController
webViewController.urlString = urlString;
}
[self presentViewController:webViewController animated:YES completion:nil];
}
For, extra checks, you can also check that the url is valid or not like pinging to it and checking for it whether it responds or not.
You can create a category:
#interface NSString (NSStringValidator)
- (BOOL)isValidEmail;
- (BOOL)isValidURL;
#end
#implementation NSString (NSStringValidator)
- (BOOL)isValidEmail {
NSString *regExpPattern = #"\\b([a-zA-Z0-9%_.+\\-]+)#([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b";
NSError *errorNext = NULL;
NSRegularExpression *regexNext = [NSRegularExpression regularExpressionWithPattern:regExpPattern
options:NSRegularExpressionCaseInsensitive
error:&errorNext];
NSRange range = [regexNext rangeOfFirstMatchInString:self
options:NSRegularExpressionCaseInsensitive
range:NSMakeRange(0, self.length)];
return NSEqualRanges(range, NSMakeRange(0, self.length));
}
- (BOOL)isValidURL {
NSString *regExpPattern = #"(?i)(?:(?:https?):\\/\\/)?(?:\\S+(?::\\S*)?#)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?";
NSError *errorNext = NULL;
NSRegularExpression *regexNext = [NSRegularExpression regularExpressionWithPattern:regExpPattern
options:NSRegularExpressionCaseInsensitive
error:&errorNext];
NSRange range = [regexNext rangeOfFirstMatchInString:self
options:NSRegularExpressionCaseInsensitive
range:NSMakeRange(0, self.length)];
return NSEqualRanges(range, NSMakeRange(0, self.length));
}
#end
Then call category method:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
[theTextField resignFirstResponder];
if (theTextField.text.isValidURL) {
//open site
} else {
//search text
}
return YES;
}

Zbar sdk scanner not working properly

In my application i have integrated Zbar SDK scanner, while scanning usually its working fine but my case is some times didfinishpickingmediawithInfo: delegate method firing twice. Here is my code which is in a singletone class.
-(void)scanProductBarCode
{
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
reader.supportedOrientationsMask = ZBarOrientationMaskLandscape;
else
reader.supportedOrientationsMask = ZBarOrientationMaskPortrait;
ZBarImageScanner *scanner = reader.scanner;
[scanner setSymbology: ZBAR_UPCA config: ZBAR_CFG_ENABLE to: 1];
[scanner setSymbology: ZBAR_CODE39 config: ZBAR_CFG_ADD_CHECK to: 0];
}
#pragma mark - Scanner delegate methods
- (void) imagePickerController: (UIImagePickerController*) reader didFinishPickingMediaWithInfo: (NSDictionary*) info
{
id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
break;
barCodeString = [[NSString alloc] initWithString:symbol.data];
if(self.delegate)
[self.delegate getBarcodeString:barCodeString];
[reader dismissModalViewControllerAnimated:YES];
}
See this screen shot:
At background the scanner is still running like this in twice occuring case..
I ran into the same problem. I added a BOOL instance variable to my class named _processing. Then I did this:
- (void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*)info
{
if (_processing) return;
id<NSFastEnumeration> results = [info objectForKey:ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results) {
_processing = YES;
barCodeString = symbol.data;
if(self.delegate) {
[self.delegate getBarcodeString:barCodeString];
}
break;
}
[reader dismissModalViewControllerAnimated:YES];
}
This ensures that only the first call is processed. You may need to reset _processing if you plan to reuse the view controller more than once.
Since the ZBarReaderViewController scans the image in continuous mode, it could be that the image is scanned twice before you dismiss the ZBarReaderViewController. You may try making the reader (ZBarReaderViewController *reader ) an instance variable of your class, and in the delegate method:
- (void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*)info
{
// Stop further scanning
[reader.readerView stop];
...
//Continue with processing barcode data.
}

Resources