App terminates on back button - iphone

I have a view controller "Gallery screen" namely, as user taps button "Gallery" it goes to that view controller. Now I have a web service call if any picture of particular outlet exists fetch it or else if it doesn't exist then show an AlertView saying "No image found". Now my problem is when user go to gallery screen if there is no image of that outlet and user hits back button before response of service "no image found" app terminates. I get that popup saying "no image found" on previous screen that i get after pressing back button as i "Ok" it, it terminates but THIS ONLY HAPPENS IN iOS 7. Please help and thanks in advance.
EDIT:
I have also tried to dealloc my objects but still the same issue. May be I'm missing something here is the code that I used.
-(void)dealloc
{
bllGalleryImages.delegate = nil;
bllGalleryImages = nil;
}
here is my viewDidLoad Method
-(void)viewDidLoad
{
[super viewDidLoad];
progress = [[MBProgressHUD alloc] init];
progress.labelText = #"Loading";
[progress showUsingAnimation:YES];
[self.view addSubview:progress];
scrl = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
scrl.scrollEnabled = YES;
scrl.minimumZoomScale=1.0;
scrl.maximumZoomScale=4.0;
scrl.delegate=self;
// Do any additional setup after loading the view from its nib.
}
here is my View will appear method
-(void)viewWillAppear:(BOOL)animated
{
[self userInterface];
[self callService];
}
here is my callService method
-(void)callService
{
NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
[param setObject:#"xyz" forKey:#"DeveloperKey"];
[param setObject:outletObjForInfo.outlet_id forKey:#"outletID"];
bllGalleryImages = [[BLLAuthentication alloc] init];
bllGalleryImages.delegate = self;
[bllGalleryImages getGalleryImages:param];
}

Related

How to navigate the view in iphone programming?

In my appController's ViewDidLoad, I have done some thing as below
- (void)viewDidLoad
{
self.overlayViewController =
[[[OverlayViewController alloc] initWithNibName:#"OverlayViewController" bundle:nil] autorelease];
// as a delegate we will be notified when pictures are taken and when to dismiss the image picker
self.overlayViewController.delegate = self;
self.capturedImages = [NSMutableArray array];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
// camera is not on this device, don't show the camera button
NSMutableArray *toolbarItems = [NSMutableArray arrayWithCapacity:self.myToolbar.items.count];
[toolbarItems addObjectsFromArray:self.myToolbar.items];
[toolbarItems removeObjectAtIndex:2];
[self.myToolbar setItems:toolbarItems animated:NO];
}
}
I have two methods as below,
- (IBAction)cameraAction:(id)sender
{
[self showImagePicker:UIImagePickerControllerSourceTypeCamera];
}
- (void)showImagePicker:(UIImagePickerControllerSourceType)sourceType
{
if (self.imageView.isAnimating)
self.imageView.stopAnimating;
if (self.capturedImages.count > 0)
[self.capturedImages removeAllObjects];
if ([UIImagePickerController isSourceTypeAvailable:sourceType])
{
[self.overlayViewController setupImagePicker:sourceType];
[self presentModalViewController:self.overlayViewController.imagePickerController animated:YES];
}
}
Now as I click the button, the method will launch the class showing custom view, I want to call this without clicking the button, what should I do ?
I wrote the button coding directly in ViewDidLoad, but not working at all
This code, I took from apple's documentation as example
Help !
If I understand correctly, you are wanting to show a view?
If so you could push using:
[self.navigationcontroller pushviewcontroller:YOURVIEWCONTROLLER animated:YES];
Or you could present it using:
[self presentModalViewControllerpushviewcontroller:YOURVIEWCONTROLLER animated:YES];

Adding a UIActivityIndicator to a modal view (ELCimagepicker)

I've added the ELCimagepicker (https://github.com/Fingertips/ELCImagePickerController) to my project and it works perfectly, allowing the user to select multiple images for a slideshow. But when you click 'Save', there can be a lengthy delay depending on how many photos were added.
I've been trying to add a UIActivityIndicator when the user clicks 'Save', but having trouble due to the modal view that is presented. I can call a method from the activity that ELCimagepicker presents (ELCImagePickerController) and this gets actioned by the activity handling the presenting of the image picker. But whenever I try to add to the view, it isn't shown as the modal is on top of the activity indicator.
I've tried using bringSubviewToFront, I've tried adding the code directly to the imagepicker method file with [[self parentViewController] addSubView], but no luck.
Here's the latest code I tried: (indicator is declared in the .h file as UIActivityIndicator *indicator)
indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.hidden=false;
[self.navigationController.view addSubview:self.indicator];
[self.navigationController.view bringSubviewToFront:self.indicator];
[indicator startAnimating];
if([delegate respondsToSelector:#selector(elcImagePickerController:showIndicator:)]) {
[delegate performSelector:#selector(elcImagePickerController:showIndicator:) withObject:self withObject:#"test"];
}
Has anyone had any success with adding a UIActivityIndicator on top of the ELCimagepicker, or another modal view handled by another class?
I've tried MBProgressHUD but couldn't get that working quite right either - it would show up when I used it in the ELCimagepicker class, but crashed on removal with:
bool _WebTryThreadLock(bool), 0x42368e0: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
Any help would be fantastic.
Thanks.
I have figure out your problem. You can do this as below..
-(void)selectedAssets:(NSArray*)_assets {
UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
UIViewController * topView = [self.viewControllers objectAtIndex:[self.viewControllers count]-1];
activityIndicator.center = CGPointMake(topView.view.frame.size.width/2, topView.view.frame.size.height/2);
[activityIndicator setHidden:NO];
[topView.view addSubview:activityIndicator];
[topView.view bringSubviewToFront:activityIndicator];
[activityIndicator startAnimating];
[self performSelector:#selector(doProcess:) withObject:_assets afterDelay:2.1];
}
- (void) doProcess:(NSArray *)_assets {
NSMutableArray *returnArray = [[[NSMutableArray alloc] init] autorelease];
for(ALAsset *asset in _assets) {
NSMutableDictionary *workingDictionary = [[NSMutableDictionary alloc] init];
[workingDictionary setObject:[asset valueForProperty:ALAssetPropertyType] forKey:#"UIImagePickerControllerMediaType"];
[workingDictionary setObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]] forKey:#"UIImagePickerControllerOriginalImage"];
[workingDictionary setObject:[[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]] forKey:#"UIImagePickerControllerReferenceURL"];
[returnArray addObject:workingDictionary];
[workingDictionary release];
}
[self popToRootViewControllerAnimated:NO];
[[self parentViewController] dismissModalViewControllerAnimated:YES];
if([delegate respondsToSelector:#selector(elcImagePickerController:didFinishPickingMediaWithInfo:)]) {
[delegate performSelector:#selector(elcImagePickerController:didFinishPickingMediaWithInfo:) withObject:self withObject:[NSArray arrayWithArray:returnArray]];
}
}
Let me know if this answer help you ...
Thanks,
MinuMaster
It looks like you are updating UI on a background thread. All UIKit updates are to be done in the main thread. So I recommend you execute methods doing UI updates using performSelectorOnMainThread:withObject:.
I solved the issue like this
activityIndicatorObject = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
// Set Center Position for ActivityIndicator
activityIndicatorObject.center = CGPointMake(150, 250);
activityIndicatorObject.backgroundColor=[UIColor grayColor];
// Add ActivityIndicator to your view
[self.view addSubview:activityIndicatorObject];
activityIndicatorObject.hidesWhenStopped=NO;
[activityIndicatorObject startAnimating];

How to dismiss a UIPopover correctly?

i have added a UIPopover to my navigationbar when the user touches the rightbarbuttonitem.
I want to know whats the cleanest coding for showing and dismissing the popover. With the code below, it works, but not correct.
If the user touches the rightbarbuttonitem first, the popover appears. Now he can choose a cell,.. works. Or you can touch outside the popover and it disappears. Both ways correctly.
But when touching the rightbarbuttonitem and after that, the same touch on that icon again, you have to touch it twice to bring up that popover again. (Not on the first touch).
How should that correctfunction look like? Thanks for your time..
-(void) downloads:(UIBarButtonItem*)button{
NSLog(#"downloads");
if(tableViewController == nil) {
tableViewController = [[[TableViewController alloc] initWithStyle:UITableViewStylePlain] autorelease];
self.popoverController = [[[UIPopoverController alloc] initWithContentViewController:tableViewController]autorelease] ;
[self.popoverController presentPopoverFromBarButtonItem:barButtonItem permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
tableViewController.delegate = self;
}else {
[self.popoverController dismissPopoverAnimated:NO];
tableViewController.delegate = nil;
tableViewController = nil;
//[self.popoverController release];
//self.popoverController = nil;
}
}
//delegate
-(void) selectedTable:(NSString*)text{
NSLog(#"selectedTable: %#", text);
[self.popoverController dismissPopoverAnimated:YES];
}
Comments
Your downloads: method checks for tableViewController value and make decision if UIPopoverController should be displayed or dismissed. But yours selectedTable: method does dismiss popoverController and does not set tableViewController to nil thus it doesn't work as expected by you.
And I also don't see UIPopoverControllerDelegate implementation, especially popoverControllerDidDismissPopover: which will tell you when UIPopoverController was dismissed (by touching outside your UIPopoverController for example).
Memory Management
Read memory management guide. [self.popoverController release] with self.popoverController = nil leads to crash - one release and second release during setting to nil. (I assume your popoverController property retains).
#Chiefly Izzy: Thanks for your help. You point me in the right direction.
Here´s the code i´m using. It works great. Hope that memory management is clean, too. Isn´t it?
-(void) downloads:(UIBarButtonItem*)button{
if([self.popoverController isPopoverVisible])
{
[self.popoverController dismissPopoverAnimated:YES];
[self.popoverController.delegate popoverControllerDidDismissPopover:self.popoverController];
return;
}
// PopOver Bookmarks-Icon
if(tableViewController == nil) {
tableViewController = [[PdfTableViewController alloc] initWithStyle:UITableViewStylePlain]; //autorelease];
self.popoverController = [[UIPopoverController alloc] initWithContentViewController:tableViewController]; //autorelease] ;
[self.popoverController presentPopoverFromBarButtonItem:barButtonItem permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
popoverController.delegate = self;
tableViewController.delegate = self;
}
/* Using "isPopoverVisible" from top or that else. both works
else {
[self.popoverController dismissPopoverAnimated:YES];
[self.popoverController.delegate popoverControllerDidDismissPopover:self.popoverController];
}
*/
}
-(void) selectedTableView:(NSString*)text{
NSLog(#"selectedTableView: %#", text);
[self.popoverController dismissPopoverAnimated:YES];
[self.popoverController.delegate popoverControllerDidDismissPopover:self.popoverController];
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popover{
NSLog(#"popoverControllerDidDismissPopover");
tableViewController.delegate = nil;
[tableViewController release];
tableViewController = nil;
popoverController.delegate = nil;
[popoverController release];
popoverController = nil;
}

UIImagePicker view not removing itself after first use

I have an app that is adding a view that is used to call UIImagePickerController. When the use hits the add image button, the following code executes:
'- (IBAction)addPhoto:(id)sender {
// Call background tap in case any keyboards are still up
[self backgroundTap:sender];
if (jpegData) {
// If we already chose an image, don't allow to choose another.
// Have to cancel out and come back!
return;
}
// Shows the photo picker so the user can take or select an image
photoPickerViewController = [[PhotoPickerViewController alloc] initWithNibName:#"PhotoPicker" bundle:nil];
photoPickerViewController.delegate = self;
// Add it to the subview - it will auto animate in/out
[self.view addSubview:photoPickerViewController.view];
}
This presents the user with a view that I created that has 3 buttons: Take photo, choose existing photo, and cancel. Cancel just cancels back to the main view. If take photo or choose existing is called, this code is executed:
'- (IBAction)choosePhoto:(id)sender {
// Show an image picker to allow the user to choose a new photo.
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
if((UIButton*)sender == chooseExistingButton) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
} else {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.showsCameraControls = YES;
}
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
}
When if the user cancels out from the image picker, we go back to the main view. No problem. If however they complete image selection (either through taking a photo or choosing an existing one) then we call:
'- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Ok, dismiss the modal picker, bring up the activity indicator and dispatch a thread
// that will do all the photo processing ...
BOOL isFromCamera = picker.sourceType == UIImagePickerControllerSourceTypeCamera;
// Dismiss the picker view controller
[picker dismissModalViewControllerAnimated:NO];
// And remove our view from the list of views
[self.view removeFromSuperview];
if (isFromCamera)
{
// Declare the completion block to use
ALAssetsLibraryWriteImageCompletionBlock compBlock = ^(NSURL *assetURL, NSError *error) {
if (error != nil || assetURL == nil) {
NSLog(#"Failed to save photo: %#", error);
[delegate photoSetURLForImage:nil];
}
else {
NSLog(#"URL is : %#", [assetURL absoluteString]);
[delegate photoSetURLForImage:assetURL];
}
};
ALAssetsLibrary* library = [[[ALAssetsLibrary alloc] init] autorelease];
[library writeImageToSavedPhotosAlbum:cgimage
metadata:meta
completionBlock:compBlock];
return;
}
else {
// Use the URL to get the metadata for the image that was picked ...
NSURL* url = [(NSDictionary*)info objectForKey:#"UIImagePickerControllerReferenceURL"];
if (url) {
// Define a result and failure block for fetching from the ALAsset
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset* myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
NSLog(#"URL is : %#", [[rep url] absoluteString]);
[delegate photoSetURLForImage:[rep url]];
};
// And also define a failure block
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
[delegate photoSetURLForImage:nil];
};
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:url
resultBlock:resultblock
failureBlock:failureblock];
return;
}
}
// If we get here, something went very wrong
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error" message:#"An error occured while retrieving the image" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil] autorelease];
[alert show];
}
Now, the first time I run through this code, all works great. As soon as I hit "use" on the image I took with the camera, or I select an image from the camera roll, the UIImagePicker view and the view that launches it go away and I'm back at the main view while I wait for the ALAsset calls to do their thing.
The problem starts when I try to repeat this process a second time. After selecting an image or taking one, the processing begins, but the views do not go away, until all of the processing by the ALAsset calls has completed. I can't figure out why this is. Why it works the first time, but not anytime after. Is there some caching mechanism I have to clear? Anyways, if anybody can offer up some advice, I'd be very grateful.
Thanks,
J
Yet again it appears I'll be answering my own question. This is starting to become a habit lol.
So it appears that the ALAsset calls aren't spinning off a new thread which is what I thought they were supposed to do. My bad. So to resolve, it was just a matter of spawning a new thread to do all the ALAsset stuff, and in the main thread dismissing my picker and what not.
Problem solved, yay!

Exception in iPhone app : Modal transition is already in progress

I have what I believe is a fairly simple application at the moment based on a few tutorials cobbled together. I'm using XCode 3.2.3 in OSX 10.6.4. It started as a standard iPhone "Window Based Application". Using interface builder I have added a Tab Bar Controller using the O'Reilly video tutorial here:
http://broadcast.oreilly.com/2009/06/tab-bars-and-navigation-bars-t.html
In the first Tab I have a standard UIView with two buttons. Both call the same function to display a UIImagePickerController:
-(IBAction) btnPhotoClicked:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
if((UIButton *)sender == btnChoosePhoto)
{
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
} else {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
}
I am running the code inside an emulator so only ever click the button called Choose Photo. When the dialogue is released with a photo chosen this function runs:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *mediaUrl;
mediaUrl = (NSURL *)[info valueForKey:UIImagePickerControllerMediaURL];
if (mediaUrl == nil)
{
imagePuzzle = (UIImage *) [info valueForKey:UIImagePickerControllerEditedImage];
if(imagePuzzle == nil)
{
//--- Original Image was selected ---
imagePuzzle = (UIImage *) [info valueForKey:UIImagePickerControllerOriginalImage];
}
else {
//--- Get the edited image ---
//--- If it was successful the above valueForKey:UIImagePickerControllerEditedImage
//--- would have assigned it already.
}
}
else {
//--- Muppet selected a video
}
// Animate the picker window going away
[picker dismissModalViewControllerAnimated:YES];
ImageViewController *imageViewController = [[ImageViewController alloc] init];
imageViewController.delegate = self;
[self presentModalViewController:imageViewController animated:YES];
[imageViewController release];
}
This is where my problem lies. I've tried many different hacks and iterations but the above code is the simplest to present the problem. When the imageViewController is displayed as a modal dialogue the following exception is thrown:
2010-07-09 15:29:29.667 Golovomka[15183:207] *** Terminating app due to uncaught
exception 'NSInternalInconsistencyException', reason: 'Attempting to begin a modal
transition from <NewViewController: 0x5915f80> to <ImageViewController: 0x594a350>
while a transition is already in progress. Wait for viewDidAppear/viewDidDisappear
to know the current transition has completed'
How do I cure this? I have tried delays and other tricks but do not really understand how I'm supposed to use viewDidAppear or viewDidDisappear to help me. Also of note is that a very basic application with one view loading the picker then displaying another view with the image in does not produce the error. Any help gratefully received.
To address the specific issue described here, you could add the viewDidAppear method in your class:
-(void)viewDidAppear:(BOOL)animated
{
if (/*just visited ImagePicker*/)
{
ImageViewController *imageViewController = [[ImageViewController alloc] init];
imageViewController.delegate = self;
[self presentModalViewController:imageViewController animated:YES];
[imageViewController release];
}
}
Remove those lines from below your call:
[picker dismissModalViewControllerAnimated:YES];
So, whenever your class self appears (is displayed), it will call viewDidAppear... Since this most likely isn't really what you want all the time, you could add some variables to set/clear that defines whether or not to immediately present the imageViewController when self is displayed. Something like "If coming from image picker, show the imageViewController, otherwise do nothing".
That said, imho, pushing modal views is should generally be done in response to a user action and I would maybe rethink the user experience here - e.g. add a subview instead of pushing a modal view which you could do where your currently have the code - but if you're just playing around with some tutorials that should solve the NSInternalInconsistencyException. :) Cheers!
In iOS 5.0 and above you can use
[self dismissViewControllerAnimated:YES completion:^{
//present another modal view controller here
}];
I ran into this issue quite a few times. I recently started using this simple fix:
When I am going to present a new modal view controller immediately after dismissing another modal view controller, I simply dismiss the first one with argument NO in dismissModalViewControllerAnimated:.
Since the second view is presented with an animation, you hardly notice that the first one goes away fast. And you never get the transitions conflict.
I was having the same problem when i wanted to present an MFMailComposeViewController immediately after dismissing the UIImagePickerController. Heres what i did:
I removed the [imagePicker release]; statement from where i was presenting the image picker and put it in didFinishPickingMedia callback.
I used [self performSelector:#selector(presentMailComposer:) withObject:image afterDelay:1.0f];
Here's my code:
Displaying Image Picker
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
NSArray *media = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
if ([media containsObject:(NSString*)kUTTypeImage] == YES) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
[picker setMediaTypes:[NSArray arrayWithObject:(NSString *)kUTTypeImage]];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
[self presentModalViewController:picker animated:YES];
//[picker release];
}
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Unavailable!"
message:#"Could not open the Photo Library."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
Image Picker Delegate Callback - didFinishPickingMedia
NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
UIImage *photoTaken = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//Save Photo to library only if it wasnt already saved i.e. its just been taken
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(photoTaken, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
}
//Pull up MFMailComposeView Controller
[self performSelector:#selector(composeMailWithPhoto:) withObject:photoTaken afterDelay:1.0f];
}
[picker dismissModalViewControllerAnimated:YES];
[picker release];
Display Mail Composer View
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
// Fill out the email fields and Attach photograph to mail
static NSString *imageType = #"image/jpeg";
NSString *imageName = [NSString stringWithString:#"MyCoffeeCup.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
[mailPicker addAttachmentData:imageData mimeType:imageType fileName:imageName];
[mailPicker setToRecipients:[NSArray arrayWithObject:#"hello#xische.com"]];
[self presentModalViewController:mailPicker animated:YES];
//[self.navigationController pushViewController:mailPicker animated:YES];
[mailPicker release];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Unavailable!"
message:#"This device cannot send emails."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}