I can not use sourceType as UIImagePickerControllerSourceTypePhotoLibrary in ZBarSDK - photolibrary

I download ZBarSDK 1.2 in http://zbar.sourceforge.net/download.html
It works well when I set the sourceType of ZBarReaderViewController as UIImagePickerControllerSourceTypeCamera.
But when I set the sourceType as UIImagePickerControllerSourceTypePhotoLibrary or UIImagePickerControllerSourceTypeSavedPhotosAlbum,the app crashed and I got the error as follow:
2012-05-28 17:23:03.476 Wow[4137:10703] * Assertion failure in
-[ZBarReaderViewController setSourceType:], /Users/spadix/zbar/hg/sdk/iphone/ZBarReaderViewController.m:650
2012-05-28 17:23:03.626 Wow[4137:10703] * Terminating app due to
uncaught exception 'NSInternalInconsistencyException', reason:
'attempt to set unsupported value (1) for sourceType property'
I have google this issue but can't find a solution.Can anybody tell me how to solute this issue?Dose version 1.2 only support UIImagePickerControllerSourceTypeCamera?Dose the source witch I download is bad?
Thanks.

Basically present the standard iOS media view controller if you want to choose a saved image. After the user has selected an image from the standard iOS media controller, you instantiate a copy of ZBarImageScanner to scan the image. If this makes sense, skip to step 5 to see how I scan a UIImage using ZBarImageScanner. Otherwise, try and follow along the steps below. Hope this helps.
First show the user an alert with options.
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:#"" delegate:self
cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Camera", #"Camera Roll", #"Photo Library", nil];
[sheet showInView:self.view];
On selection,
- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex {
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
switch (buttonIndex) {
case 0: sourceType = UIImagePickerControllerSourceTypeCamera; break;
case 1: sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; break;
case 2: sourceType = UIImagePickerControllerSourceTypePhotoLibrary; break;
default: break;
}
if ( buttonIndex <= 2 ) {
[self presentBarcodeReader:sourceType];
}
}
if and only if the sourceType == UIImagePickerControllerSourceTypeCamera do you use ZBar to present the image capture interface.
- (void)presentBarcodeReader:(UIImagePickerControllerSourceType)sourceType {
if ( sourceType == UIImagePickerControllerSourceTypeCamera ) {
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.showsZBarControls = YES;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
ZBarImageScanner *scanner = reader.scanner;
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
[self presentModalViewController:reader animated:YES];
} else {
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = sourceType;
mediaUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
mediaUI.allowsEditing = NO;
mediaUI.delegate = self;
[self presentModalViewController:mediaUI animated:YES];
}
}
a couple ways we can detect which media picker was used
- (void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*)info {
id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
if ( results ) {
ZBarSymbol *symbol = nil;
for (symbol in results) break;
[reader dismissViewControllerAnimated:YES completion:^{
[self partLookup:symbol.data];
}];
} else {
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage] ? [info objectForKey:UIImagePickerControllerEditedImage] : [info objectForKey:UIImagePickerControllerOriginalImage];
[self scanImage:image];
}
}
and the juicy part
- (void)scanImage:(UIImage*)image {
ZBarImage *zImage = [[ZBarImage alloc] initWithCGImage:image.CGImage];
ZBarImageScanner *scanner = [[ZBarImageScanner alloc] init];
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
[scanner scanImage:zImage];
ZBarSymbolSet *set = [scanner results];
for (ZBarSymbol *symbol in set) {
NSLog(#"%#", symbol.data);
// process symbol.data however you please.
}
}

Related

Map Issue for MKAnnotationView in iOS 7 and iOS 8

I use iOS SDK 8 and having problem to display annotation for certain locations but it is working fine for some locations.
For those failed location, it keeps looping at if (pinView == nil) and the app will quit unexpectedly, any idea for the root caused?
- (void)populateAllLocation {
self.locations = [selectedCountry_.locations allObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"latitude != nil && longitude != nil"];
self.locations = [[selectedCountry_.locations filteredSetUsingPredicate:predicate] allObjects];
[mapView_ addAnnotations:locations_];
[self centralizeMap];
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:MKUserLocation.class]) {
static NSString *PinIdentifier = #"UserLocationPin";
MKAnnotationView *pinView =
[mapView_ dequeueReusableAnnotationViewWithIdentifier:PinIdentifier];
if (pinView == nil) {
pinView =
[[[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:PinIdentifier] autorelease];
pinView.canShowCallout = YES;
pinView.image = [UIImage imageNamed:#"mylocation_pin"];
}
[self populateAllLocation];
return pinView;
}
Your populateAllLocation is triggering display of the annotation views, but the delegate method itself calls populateAllLocation so you have a loop. You should only be returning annotation views in the delegate, not altering the map.

FBLoginView: login isn't performed

I'm adding FBLoginView to my ViewController < FBLoginViewDelegate >:
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;
[self.view addSubview:loginview];
[loginview sizeToFit];
All the necessary fields in plist (FacebookAppID, FacebookDisplayName, URL Schemes) are all set according to the tutorial. The facebook app is also configured according to the tutorial (bundle ID is set, Facebook login is enabled).
But the login still isn't performed. When I press on "log in", I get redirected to the browser with facebook login, but when it's finished, I'm not logged in the app (loginViewFetchedUserInfo:user: isn't called, "log in" hasn't changed to "log out").
What can be the problem?
Everything worked after I implemented the following in the AppDelegate.m (taken from one of the official examples):
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
//NSLog(#"User session found");
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
self.loggedInUserID = user.id;
self.loggedInSession = FBSession.activeSession;
}
}];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:FBSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
/*
*
*/
- (void) closeSession {
[FBSession.activeSession closeAndClearTokenInformation];
}
/*
* If we have a valid session at the time of openURL call, we handle
* Facebook transitions by passing the url argument to handleOpenURL
*/
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
}
You need to add the following to the app delegate
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
// You can add your app-specific url handling code here if needed
return wasHandled;
}
You may need to implement the
(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url method
Be sure to call:
return [FBSession.activeSession handleOpenURL:url];
When applicable.
#Sergey: Are you want to open FBDialog on your native app or in browser? If you to want open in your native app then use "FBSessionLoginBehaviorForcingWebView". Here is my code that I am using:
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permission];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self yourmethod];
break;
case FBSessionStateClosedLoginFailed: {
// prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
if(error.code == 2) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:#"FBAlertTitle"
message:#"FBAuthenticationErrorMessage"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
or you want to open in browser then use following :
In your .h file
#import <FacebookSDK/FacebookSDK.h> and add FBLoginViewDelegate delegate
In you .m file
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;
[self.view addSubview:loginview];
[loginview sizeToFit];
// use following delegate methods
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
// first get the buttons set for login mode
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
// here we use helper properties of FBGraphUser to dot-through to first_name and
// id properties of the json response from the server; alternatively we could use
// NSDictionary methods such as objectForKey to get values from the my json object
NSLog(#"userprofile:%#",user);
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
//BOOL canShareAnyhow = [FBNativeDialogs canPresentShareDialogWithSession:nil];
}
- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error {
// see https://developers.facebook.com/docs/reference/api/errors/ for general guidance on error handling for Facebook API
// our policy here is to let the login view handle errors, but to log the results
NSLog(#"FBLoginView encountered an error=%#", error);
}

Storing CLLocation (latitude, longtitude data) in to Core Data

i want to ask a question about core location and core data. i looked some questions but couldnt do that..
i have a application which stores some textfields, photos, date and time datas in UITableView With core data, i stored everything (photos, texts, date etc.) Now trying to store Location data i couldnt do.
this is some of my code here.
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSDateFormatter *myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:#"MM-dd-yyyy HH:mm"];
[myFormatter setTimeZone:[NSTimeZone systemTimeZone]];
todaysDate = [myFormatter stringFromDate:[NSDate date]];
myDateLabel.text = todaysDate;
UIView *patternBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
patternBg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background01.png"]];
self.tableView.backgroundView = patternBg;
// If we are editing an existing picture, then put the details from Core Data into the text fields for displaying
if (currentPicture)
{
[companyNameField setText:[currentPicture companyName]];
[myDateLabel setText:[currentPicture currentDate]];
if ([currentPicture photo])
[imageField setImage:[UIImage imageWithData:[currentPicture photo]]];
}
}
in the saveButton
- (IBAction)editSaveButtonPressed:(id)sender
{
// For both new and existing pictures, fill in the details from the form
[self.currentPicture setCompanyName:[companyNameField text]];
[self.currentPicture setCurrentDate:[myDateLabel text]];
[self.currentPicture setCurrentTime:[myTimeLabel text]];
[self.currentPicture setLatitudeData:[_latitudeLabel text]];
[self.currentPicture setLongtidueData:[_longtitudeLabel text]];
}
and last one, my locationManager's method..
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
_longtitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
[self->locationManager stopUpdatingLocation];
}
}
i tried "[locationmanager stopUpdatingLocation];" many times, but when i entered the app, code starts to calculating latitude and longtitude data, i just want to take that data 1 time, and store..
Thanks!
If calling stopUpdatingLocation doesn't stop location updates, then most likely self->locationManager is nil. That would mean you're not really making the call.
It's hard to be sure exactly why this would happen, except that your code seem to make a point of not using any semantics implied by a #property declaration. Just assigning to location in viewDidLoad avoids any declaration, and looking up the manager using self->locationManager does as well. Assuming that location is a property, you should assign it to self.locationManager, and use that when looking it up as well.
A couple things:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5) return; // ignore cached location, we want current loc
if (newLocation.horizontalAccuracy <= 0) return; // ignore invalid
// wait for GPS accuracy (will be < 400)
if (newLocation.horizontalAccuracy < 400) {
_longtitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.latitude];
[manager stopUpdatingLocation];
}
}
In your didUpdateToLocation do this code
(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5) return;
// ignore cached location, we want current loc
if (newLocation.horizontalAccuracy <= 0) return; // ignore invalid
// wait for GPS accuracy (will be < 400)
if (newLocation.horizontalAccuracy < 400) {
_longtitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.latitude];
[manager stopUpdatingLocation];
//assign nil to locationManager object and delegate
locationManager.delegate = nil;
locationManager = nil;
}
}
Thanks.

Find assets in library - add to a AVMutableComposition - export = crash

I've been struggling with adding assets from the iPhone Photo Library to a AVMutableComposition and then export them. Here is what I got:
Finding the assets: (here I grab the AVURLAsset)
-(void) findAssets {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just videos.
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop){
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
NSURL *url = [representation url];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
// Do something interesting with the AV asset.
[thumbs addObject:alAsset];
[assets addObject:avAsset];
}else if(alAsset == nil){
[self createScroll];
}
}];
}
failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
NSLog(#"No groups");
}];
[library release];
}
Here I add a asset to my composition (I use the first object in the array for testing only.
-(void) addToCompositionWithAsset:(AVURLAsset*)_asset{
NSError *editError = nil;
composition = [AVMutableComposition composition];
AVURLAsset* sourceAsset = [assets objectAtIndex:0];
Float64 inSeconds = 1.0;
Float64 outSeconds = 2.0;
// calculate time
CMTime inTime = CMTimeMakeWithSeconds(inSeconds, 600);
CMTime outTime = CMTimeMakeWithSeconds(outSeconds, 600);
CMTime duration = CMTimeSubtract(outTime, inTime);
CMTimeRange editRange = CMTimeRangeMake(inTime, duration);
[composition insertTimeRange:editRange ofAsset:sourceAsset atTime:composition.duration error:&editError];
if (!editError) {
CMTimeGetSeconds (composition.duration);
}
}
And finally I export the comp and here it crashes
-(void)exportComposition {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];
NSLog (#"can export: %#", exportSession.supportedFileTypes);
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
NSString *exportPath = [documentsDirectoryPath stringByAppendingPathComponent:EXPORT_NAME];
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
exportSession.outputURL = exportURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;//#"com.apple.quicktime-movie";
[exportSession exportAsynchronouslyWithCompletionHandler:^{
NSLog (#"i is in your block, exportin. status is %d",
exportSession.status);
switch (exportSession.status) {
case AVAssetExportSessionStatusFailed:
case AVAssetExportSessionStatusCompleted: {
[self performSelectorOnMainThread:#selector (exportDone:)
withObject:nil
waitUntilDone:NO];
break;
}
};
}];
}
Does anyone have an idea of what it might be? It crashes on
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];
And I tried different presets and outputFileTypes.
Thanks
* SOLVED *
I have to answer my own question now when I have solved. It's amazing that I've been struggling with this for a whole day and then I fix it right after posting a question :)
I changed and moved:
composition = [AVMutableComposition
composition];
to:
composition = [[AVMutableComposition
alloc] init];
I think I was too tired when I was working on this yesterday. Thanks guys!

Mapkit Annotation type when zooming in and out?

i am working with Mapkit and i am on SDK 4.2, i am having a strange bug here, in fact i have 3 annotation types, "blue.png", red.png,black.png. I am loading these by a flux and depending on the type its will select these annotation types. Everything works fine when the map is loaded i have the the different annotation view, but when i move , zoom in or zoom out the annotation view changes i.e where it was supposed to be blue.png it becomes black.png.
I am actually testing it on device.
Thank you very much :)
Hey veer the problem is that this method is called if the user pans the map to view another location and then comes back to the place where the annotations are plotted.
- (MKAnnotationView *)mapView:(MKMapView *)mapview viewForAnnotation:(id <MKAnnotation>)annotation
I have seen many sample code for map application and this in what most of the people are using.
- (MKAnnotationView *)mapView:(MKMapView *)mapview viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if(annotationView)
return annotationView;
else
{
MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.draggable = YES;
pinView.pinColor = MKPinAnnotationColorGreen;
return pinView;
}
return nil;
}
i found the solution - in fact i am using a custom annotation view and having 3 diff types of images :
Soln:
- (AnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
AnnotationView *annotationView = nil;
// determine the type of annotation, and produce the correct type of annotation view for it.
AnnotationDetails* myAnnotation = (AnnotationDetails *)annotation;
if(myAnnotation.annotationType == AnnotationTypeGeo)
{
// annotation for your current position
NSString* identifier = #"geo";
AnnotationView *newAnnotationView = (AnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if(nil == newAnnotationView)
{
newAnnotationView = [[[AnnotationView alloc] initWithAnnotation:myAnnotation reuseIdentifier:identifier] autorelease];
}
annotationView = newAnnotationView;
}
else if(myAnnotation.annotationType == AnnotationTypeMyfriends)
{
NSString* identifier = #"friends";
AnnotationView *newAnnotationView = (AnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if(nil == newAnnotationView)
{
newAnnotationView = [[[AnnotationView alloc] initWithAnnotation:myAnnotation reuseIdentifier:identifier] autorelease];
}
annotationView = newAnnotationView;
}
}

Resources