ios UIDocumentMenuViewController not display files - ios

I want to import file from file list.I have used UIDocumentMenuViewController to display and select file. It shows blank screen when open iCloud.
I have created UIDocumentMenuViewController which show all types of files.
UIDocumentMenuViewController *documentPickerMenu = [[UIDocumentMenuViewController alloc]
initWithDocumentTypes:#[#"public.item"]
inMode:UIDocumentPickerModeImport];
documentPickerMenu.delegate = self;
[self presentViewController:documentPickerMenu animated:YES completion:nil];
I have implemented delegate methods.
- (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker{
documentPicker.delegate = self;
[self presentViewController:documentPicker animated:YES completion:nil]; }
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
if (controller.documentPickerMode == UIDocumentPickerModeImport)
{
// Condition called when user download the file
NSData *fileData = [NSData dataWithContentsOfURL:url];
// NSData of the content that was downloaded - Use this to upload on the server or save locally in directory
//Showing alert for success
dispatch_async(dispatch_get_main_queue(), ^{
NSString *alertMessage = [NSString stringWithFormat:#"Successfully downloaded file %#", [url lastPathComponent]];
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#"UIDocumentView"
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alertController animated:YES completion:nil];
});
} }
I have images on iCloud.I have tried same thing by creating UIDocumentPickerViewController instead of UIDocumentMenuViewController but same issu.I am not able to identify issue can anyone have any idea?

Related

Dialog in IOS in objective C

I have a button to share my app's link. I want a dialog box for it. I have searched a lot for it but haven't found a satisfactory solution. How can I share my application link to different social platforms, like Facebook, Twitter or Gmail?
I'm using this code:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *textToShare = #"Look at this awesome website for aspiring iOS Developers!";
NSURL *myWebsite = [NSURL URLWithString:#"My URL"];
NSArray *objectsToShare = #[textToShare, myWebsite];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypePostToFacebook,
UIActivityTypePostToTwitter,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo];
activityVC.excludedActivityTypes = excludeActivities;
[self presentViewController:activityVC animated:YES completion:nil];
// Do any additional setup after loading the view.
}
You can create your Share Action Button directly from Interface Builder and ctrl drag it into your code.
Then you can do something like this :
- (IBAction)shareByFacebook:(id)sender {
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[self generateMessage:controller];
}else{
UIAlertView* facebookAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.FB.title", #"") message:NSLocalizedString(#"Social.Account.FB.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[facebookAlert show];
}
}
This method share an image and a corresponding text message to Facebook.
- (IBAction)shareByTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[self generateMessage:tweetSheet];
}else{
UIAlertView* twitterAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.Twitter.title", #"") message:NSLocalizedString(#"Social.Account.Twitter.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[twitterAlert show];
}
}
Same for Twitter.
Don't forget to import #import <Social/Social.h>
I have created a generic generateMessage method in order to avoid code repetition.
-(void)generateMessage:(SLComposeViewController *)controller
{
if ([controller.serviceType isEqualToString:SLServiceTypeTwitter]) {
NSString* message = #"The message you want."
[controller setInitialText:message];
}
[controller setCompletionHandler:^(SLComposeViewControllerResult result) {
if (result == SLComposeViewControllerResultDone) {
DDLogInfo(#"Posted");
} else if (result == SLComposeViewControllerResultCancelled) {
DDLogInfo(#"Post Cancelled");
} else {
DDLogInfo(#"Post Failed");
}
}];
[self.parentVC presentViewController:controller animated:YES completion:nil];
}
Those methods enable you to share content (images, photos, message..) to your Facebook/Twitter and Google account directly from your app.
N.B: For Google it's a little bit different because their share method is now deprecated
Share Google+ iOS
But you can use the old way, like this example in order to share an URL for example :
- (void)showGooglePlusShare:(NSURL*)shareURL {
// Construct the Google+ share URL
NSURLComponents* urlComponents = [[NSURLComponents alloc]
initWithString:#"https://plus.google.com/share"];
urlComponents.queryItems = #[[[NSURLQueryItem alloc]
initWithName:#"url"
value:[shareURL absoluteString]]];
NSURL* url = [urlComponents URL];
if ([SFSafariViewController class]) {
// Open the URL in SFSafariViewController (iOS 9+)
SFSafariViewController* controller = [[SFSafariViewController alloc]
initWithURL:url];
controller.delegate = self;
[self.parentVC presentViewController:controller animated:YES completion:nil];
} else {
// Open the URL in the device's browser
[[UIApplication sharedApplication] openURL:url];
}
}
EDIT :
You can create only 1 IBAction button in order to share to social network.
And then the user has to choose which one.
The result will be something like this :
And the code example :
- (IBAction)shareContentSocialNetwork:(id)sender
{
if ([UIAlertController class]){
// ios 8 or higher
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"" message:#"Share on Social Network" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* fb = [UIAlertAction actionWithTitle:#"Facebook" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
// Create a method in order to add image, text etc..
[self generateMessage:controller];
}else{
UIAlertView* facebookAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.FB.title", #"") message:NSLocalizedString(#"Social.Account.FB.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[facebookAlert show];
}
}];
[alertController addAction:fb];
UIAlertAction* twit = [UIAlertAction actionWithTitle:#"Twitter" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
// Create a method in order to add image, text etc..
[self generateMessage:controller];
}else{
UIAlertView* twitterAlert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Social.Account.Twitter.title", #"") message:NSLocalizedString(#"Social.Account.Twitter.message", #"") delegate:nil cancelButtonTitle:NSLocalizedString(#"Error.ok", #"") otherButtonTitles: nil];
[twitterAlert show];
}
}];
[alertController addAction:twit];
UIAlertAction* ggl = [UIAlertAction actionWithTitle:#"Google+" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
NSURL *url = [[NSURL alloc] initWithString:#"yourContentURL"];
[self showGooglePlusShare:url];
}];
[alertController addAction:ggl];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancel];
[self presentViewController:alertController animated:YES completion:nil];
}
}
Basically I am creating the 3 specific actions of the AlertController.
For Twitter and Facebook it is pretty straightforward, even so you have to use the generateMessage method I showed you earlier.
Hope it helps.

Integrate iCloud into ios App and Retrieve files from iCloud

I integrated iCloud into iOS app using raywenderlich https://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1
But iam unable to show all the files from iCloud to our iOS app and also need specific type of files like pdf, doc and docx
Can any one suggest me.
Follow below steps to integrate iCloud in iOS app and retrieve files.
1. Enable iCloud from your developer account.
2. Create iCloud containers entitlement at developer account.
3. Then just use below code where you want to integrate your iCloud integration.
First of all import #import and add iCloudDelegate delegate then set delegate:
// Setup iCloud
[[iCloud sharedCloud] setDelegate:self];
[[iCloud sharedCloud] setVerboseLogging:YES];
[[iCloud sharedCloud] setupiCloudDocumentSyncWithUbiquityContainer:nil];
[self showiCloudFiles];
then implementation of method showiCloudFiles below
-(void) showiCloudFiles{
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
else if ([[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == NO) {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"iCloud Disabled", #"You have disabled iCloud for this app. Would you like to turn it on again?");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
UIAlertAction* deleteButton = [UIAlertAction actionWithTitle:#"Turn On iCloud"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"userCloudPref"];
[[NSUserDefaults standardUserDefaults] synchronize];
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
}];
[alert addAction:deleteButton];
[self presentViewController:alert animated:YES completion:nil];
} else {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"Setup iCloud", #"iCloud is not available. Sign into an iCloud account on this device and check that this app has valid entitlements.");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
}];
[self presentViewController:alert animated:YES completion:nil];
}
}
After that for downloading file use UIDocumentPickerDelegate method:
#pragma mark - UIDocumentPickerDelegate
-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
if (controller.documentPickerMode == UIDocumentPickerModeImport) {
//NSLog(#"%#",url);
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent]; NSString *fileExtension = [newURL pathExtension]; if([fileExtension isEqualToString:#"zip"]) {if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do further code using fileData
}
}];
[url stopAccessingSecurityScopedResource];
}
}
For UIDocumentPicker visit this link iOS-8-UIDocumentPicker
Follow this guide
https://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1
Download sample code at
https://github.com/rwenderlich/PhotoKeeper
Check if iCloud available
- (void)initializeiCloudAccessWithCompletion:(void (^)(BOOL available)) completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_iCloudRoot = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (_iCloudRoot != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud available at: %#", _iCloudRoot);
completion(TRUE);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud not available");
completion(FALSE);
});
}
});
}
Query type of flies like pdf, doc and docx
- (NSMetadataQuery *)documentQuery {
NSMetadataQuery * query = [[NSMetadataQuery alloc] init];
if (query) {
// Search documents subdir only
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
// Add a predicate for finding the documents
NSString * filePattern = [NSString stringWithFormat:#"*.%#", PTK_EXTENSION];
[query setPredicate:[NSPredicate predicateWithFormat:#"%K LIKE %#",
NSMetadataItemFSNameKey, filePattern]];
}
return query;
}

making MFMailComposeViewController disappear upon sending

So I know that i would have to use the MFMailComposeResultSent. (At least I think that's what i'm supposed to use) This is the code that i have and it sends the email and everything fine but the mail composer stays up.
EDIT: Here is my code
if ([condition isEqual: #"Excellent"] && [MFMailComposeViewController canSendMail]) {
NSString *emailBody = [NSString stringWithFormat:#"Product:%# Make:%# Year Manufactured:%# Description:%# Condition:Excellent Email:%#",inputProduct,inputMake,inputYear,inputDescript, inputEmail];
NSArray *recipient = [NSArray arrayWithObject:#"LoveShackElectronics#gmail.com"];
MFMailComposeViewController *SuperLovedEmail = [[MFMailComposeViewController alloc]init];
[SuperLovedEmail setTitle:emailTitle];
[SuperLovedEmail setToRecipients:recipient];
[SuperLovedEmail setMessageBody:emailBody isHTML:NO];
[SuperLovedEmail setUserActivity:false];
[self presentViewController:SuperLovedEmail animated:YES completion:nil];
}
else {
UIAlertController *emailAlert = [UIAlertController alertControllerWithTitle:#"Oh No!" message:#"Your Phone is not able to send an email currently or you have not chosen a condition. Please make sure you have chosen a condition and that you are signed in through Mail" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *emailAlertAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * emailAlertAction) {}];
[emailAlert addAction:emailAlertAction];
[self presentViewController:emailAlert animated:YES completion:nil];
}
You need to set the mailComposeDelegate property of your SuperLovedEmail object to be self, then handle the didFinishWithResult message, like this:
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[controller dismissViewControllerAnimated:true completion:nil];
}
You might find it useful to evaluate the MFMailComposeResult to see whether sending actually happened.

Take a picture from the camera / gallery and save it in the core data

I have the code by which I can take a picture from the camera or from the gallery of the phone,
But I want to save the image in the core data that I find it difficult.
I read a lot about it and I'm not sure with the image as string or binary data
And how to save it and how to get it.
#property (strong) NSMutableArray *allPic;
#property (strong) NSManagedObject *Image;
#end
#implementation ViewController
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Picture"];
self.allPic = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}
-(void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)takePic:(id)sender {
// ALERT SHEET.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//CAMERA
UIAlertAction *openCamrea = [UIAlertAction actionWithTitle:#"צלם" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
// If device has no camera.
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIAlertController *alertNoCamera = [UIAlertController alertControllerWithTitle:#"Error" message:#"Device has no camera" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];
[alertNoCamera addAction:ok];
[self presentViewController:alertNoCamera animated:YES completion:nil];
}
else// if have a camera.
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
}];
// GALLERY
UIAlertAction *openGallery = [UIAlertAction actionWithTitle:#"גלריה" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}];
[alert addAction:openCamrea];
[alert addAction:openGallery];
[self presentViewController:alert animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//save image
{
I think right way will be saving file in directory and storing path to CoreData. Here is how I have achieved it:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
[self.view makeToast:#"Saving Captured Image!" duration:2.0f position:#"top"];
UIImage *image = info[UIImagePickerControllerOriginalImage];
[self performSelectorInBackground:#selector(saveImage:) withObject:image];
}
}
- (void) saveImage : (UIImage *) image {
// image detail
// NSData *data = UIImagePNGRepresentation(image);
NSData *data = UIImageJPEGRepresentation(image, 1.0f);
NSString *imagePath = [self pathForMedia:MediaTypeImage name:[self getImageName:data]];
//WRITE FILE
BOOL saved = [data writeToFile:imagePath atomically:YES];
if (!saved)
return;
//Now save: `imagePath` to core Data.
}
- (NSString *) getImageName : (NSData *) imageData {
return [NSString stringWithFormat:#"%#.%#",[self getUniqueId], [self contentTypeForImageData:imageData]];
}
- (NSString *) pathForMedia : (MediaType) type name : (NSString *) name{
NSString *foldername = [NSString stringWithFormat:#"/%#/%#", ((type == MediaTypeImage) ? #"Photos" : #"Videos"), name];
return [[self getUserDocumentDir] stringByAppendingPathComponent:foldername];
}
- (NSString *)contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return #"jpg";
case 0x89:
return #"png";
case 0x47:
return #"gif";
case 0x49:
break;
case 0x42:
return #"bmp";
case 0x4D:
return #"tiff";
}
return nil;
}
- (NSString *) getUniqueId {
CFUUIDRef unqiueId = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, unqiueId);
CFRelease(unqiueId);
return [(__bridge NSString*)string stringByReplacingOccurrencesOfString:#"-"withString:#""];
}
To Save Image in Core Data:
You can store images in Core Data using the Binary Data attribute type. However you should be aware of a few things:
Always convert your UIImage to a portable data format like png or jpg For example:
NSData *imageData = UIImagePNGRepresentation(image);
Enable "Allows external storage" on this attribute
Core Data will move the data to an external file if it hits a certain threshold. This file is also completely managed by Core Data, so you don't have to worry about it.
If you run into performance issues, try moving the Binary Data attribute to a separate entity.
You should abstract the conversion to NSData behind the interface of your NSManagedObject subclass, so you don't have to worry about conversions from UIImage to NSData or vice versa.
If your images are not strongly related to the entities in your model, I would suggest storing them outside of Core Data.
To Take Images from gallery or camera:
{
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Device has no camera"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[myAlertView show];
return;
}
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//if you want to take image from gallery
//picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
//picker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:picker animated:YES completion:nil];
}
Hope this helps.

Ios uialertcontroller uiimagepicker dismiss : app crash

I have created a new app under xcode 6 and an old cold no more work.
Since iOS 8 we use UIalertcontroller to show action sheet
I use it to lauch photolibrary and select a picture but when I want to dismiss the picker, my app crash and I don't know why.
Below my code:
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
UIAlertController * uiViewActionSheet= [UIAlertController
alertControllerWithTitle:#"Action"
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* chooseExisting = [UIAlertAction
actionWithTitle:NSLocalizedString(#"CHOOSE_EXISTING",#"Choose Existing")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
//Do some thing here
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
[uiViewActionSheet dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:#"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action)
{
[uiViewActionSheet dismissViewControllerAnimated:YES completion:nil];
}];
[uiViewActionSheet addAction:chooseExisting];
[uiViewActionSheet addAction:cancel];
[self presentViewController:uiViewActionSheet animated:YES completion:nil];
Below the imagepicker function :
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.uImageProfile.image = chosenImage;
self.lstatutImage.text = #"save";
[picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
{
UIImageWriteToSavedPhotosAlbum(chosenImage, nil, nil, nil);
}
__block NSString* resultSaveImage = #"";
//Save image onthe server
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
resultSaveImage = [controllerObject saveProfileImage:self.uImageProfile.image];
dispatch_async(dispatch_get_main_queue(), ^{
if(![resultSaveImage isEqualToString:#"\"ok\""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"ERROR",#"Error") message:resultSaveImage delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
});
});
}
My code crash here :
[picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
Have you any idea ?
You're dismissing the picker, and then calling it:
[picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
if(picker.sourceType == UIImagePickerControllerSourceTypeCamera) {...
You also don't need the [uiViewActionSheet dismissViewControllerAnimated:YES completion:nil]; lines!
Try moving the dismiss line to the end. If it still crashes, it might be that the presentingViewController is not alive anymore.

Resources