2015-12-07 2 views
2

Я использую приведенный ниже код, чтобы выбрать изображение из камеры или библиотеки фотографий. В iOS 8 он красиво выбирает изображение. Но в iOS 9. отображается выборщик, но не выбирается изображение. Даже не возвращайтесь к контроллеру. При нажатии на изображение ничего не получается. Что я делаю не так.UIImagePickerController не выбирает изображение в iOS 9

- (void)showImgaePickerViewForSourceType:(UIImagePickerControllerSourceType)sourceType 
{ 
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 
    imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext; 
    imagePickerController.sourceType = sourceType; 
    imagePickerController.allowsEditing = YES; 
    imagePickerController.delegate = self; 
    self.imgPickerController = imagePickerController; 

    if (IS_IPAD) { 
     [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
      UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:self.imgPickerController]; 
      [popover presentPopoverFromRect:CGRectMake(self.view.frame.size.width/2-200, self.view.frame.size.height/2 - 300, 400, 400) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES]; 
      self.popOver = popover; 
     }]; 
    }else{ 
      [self presentViewController:self.imgPickerController animated:YES completion:NULL]; 
    } 
} 
+0

Вы внедрили методы делегата для выбора изображений? – cekisakurek

+0

Да, я заявил, что он работает правильно в iOS 8. – user2096064

+0

Покажите нам свою реализацию методов делегата. Они называются? – jcaron

ответ

0

Следуйте ниже кодирование

- (void)imagePicker 
{ 

    UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
    picker.delegate = self; 
    picker.allowsEditing = YES; 
    picker.sourceType = UIImagePickerControllerSourceTypeCamera; 
    [self presentViewController:pickerTakePhoto animated:YES completion:nil]; 
} 

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    UIImage *imagePicked = info[UIImagePickerControllerEditedImage]; 
    picker.delegate = self; 
    [picker dismissViewControllerAnimated:YES completion:nil]; 
} 
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{ 
    [picker dismissViewControllerAnimated:YES completion:NULL]; 
} 
2

UIPopoverController осуждаются в прошивке 9. Вместо этого вы должны использовать UIViewController с modalPresentationStyle набором для UIModalPresentationPopover.

Например:

UIImagePickerController *imagePickerController = ...; 
CGRect sourceRect = CGRectMake(self.view.frame.size.width/2-200, self.view.frame.size.height/2 - 300, 400, 400); 

imagePickerController.modalPresentationStyle = UIModalPresentationPopover; 
[self presentViewController:imagePickerController animated:YES completion:nil]; 
imagePickerController.popoverPresentationController.sourceRect = sourceRect; 
imagePickerController.popoverPresentationController.sourceView = self.view; 

Примечание:UIModalPresentationPopover был введен в прошивкой 8.0, если вам необходимо поддерживать до 8,0, то вам потребуется несколько условных проверок, чтобы использовать свой старый код прошивки 7, и выше в iOS 8+.

Примечание 2: Я считаю, что выше метод также достаточно умен, чтобы работать, если он должен модально представить сборщик вместо пирога на айфонах (с помощью размерных классов), поэтому я не думаю, что вы должны сделать свое IS_IPAD проверка.

1

Используйте этот код, он отлично работает в ios 9. Я использую панель действий, чтобы показать 2 варианта выбора.

-(IBAction)imagepickertapped:(id)sender 
    { 
     UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Take Photo" otherButtonTitles:@"Photo Library",nil]; 

     popup.tag =909; 
     popup.actionSheetStyle = UIActionSheetStyleBlackTranslucent; 
     [popup showInView:self.view]; 

    } 
    -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 


    if (actionSheet.tag ==909) 
{ 

    if (buttonIndex == 0) 
    { 

     if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 
     { 
      UIImagePickerController* picker = [[UIImagePickerController alloc] init]; 
      picker.sourceType = UIImagePickerControllerSourceTypeCamera; 
      // picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie,kUTTypeImage,nil]; 

      picker.delegate = self; 
      [self presentViewController:picker animated:YES completion:NULL]; 
     } 
     else 
     { 


      UIAlertView *altnot=[[UIAlertView alloc]initWithTitle:@"Camera Not Available" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
      [altnot show]; 

     } 

    } else if (buttonIndex == 1) { 

     UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
     //picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie,kUTTypeImage,nil]; 

     picker.delegate = self; 
     picker.editing = YES; 
     picker.allowsEditing = YES; 

     picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
     [self presentViewController:picker animated:YES completion:NULL]; 
    } 

} 


} 

    - (void)imagePickerController:(UIImagePickerController *)picker 
    didFinishPickingImage:(UIImage *)image 
       editingInfo:(NSDictionary *)editingInfo{ 


    [picker dismissViewControllerAnimated:YES completion:NULL]; 


imagedata = UIImageJPEGRepresentation(image, 0.3); 


Userimage.image = image; 


} 

Для IPAD пожалуйста ссылается этой ссылка

find here

2

я обнаружил, что мое приложение работало хорошо на других айфонах (будьте прошивкой 8 или 9 прошивки). Я не смог выбрать изображение из любого другого приложения. Затем я решил сбросить свой iPhone. Теперь все идеально. Это не проблема с кодом. Это был мой вопрос с iPhone.

+0

У меня была такая же проблема, как и на вопрос ... Затем перезагрузили мой телефон ... И это сработало! o.o –

0

Поскольку действия листы являются устаревшими и UIAlertController нужно использовать, я пишу подобный ответ в пользу новичков:

- (IBAction)attachImageTapped:(id)sender 
{ 
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Attach image" message:@"" preferredStyle:UIAlertControllerStyleActionSheet]; 
    UIAlertAction* pickFromGallery = [UIAlertAction actionWithTitle:@"Take a photo" 
                   style:UIAlertActionStyleDefault 
                  handler:^(UIAlertAction * action) { 
                   if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 
                   { 
                   UIImagePickerController* picker = [[UIImagePickerController alloc] init]; 
                   picker.sourceType = UIImagePickerControllerSourceTypeCamera; 
                   picker.delegate = self; 
                   [self presentViewController:picker animated:YES completion:NULL]; 
                   } 

                  }]; 
    UIAlertAction* takeAPicture = [UIAlertAction actionWithTitle:@"Choose from gallery" 
                   style:UIAlertActionStyleDefault 
                  handler:^(UIAlertAction * action) { 
                   UIImagePickerController* picker = [[UIImagePickerController alloc] init]; 
                   picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
                   picker.delegate = self; 
                   [self presentViewController:picker animated:YES completion:NULL]; 
                  }]; 
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" 
                  style:UIAlertActionStyleCancel 
                 handler:^(UIAlertAction * action) { 
                 }]; 

    [alertController addAction:pickFromGallery]; 
    [alertController addAction:takeAPicture]; 
    [alertController addAction:cancel]; 
    [self presentViewController:alertController animated:YES completion:nil]; 
} 

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info 
{ 
    UIImage *imagePicked = info[UIImagePickerControllerOriginalImage]; 
    [picker dismissViewControllerAnimated:YES completion:nil]; 
} 

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{ 
    [picker dismissViewControllerAnimated:YES completion:nil]; 
} 
0

, пожалуйста, следуйте этому ниже шагов для получения изображений из библиотеки и вы можете взять изображение с камеры, используя «UIAlertController» вы просто поместите следующий код в вашей кнопки событий щелчка

- (IBAction)yourButtonClickEvent:(id)sender { 

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Attach image" message:@"" preferredStyle:UIAlertControllerStyleActionSheet]; 
UIAlertAction* pickFromGallery = 
[UIAlertAction actionWithTitle:@"Take a photo" 
         style:UIAlertActionStyleDefault 
         handler:^(UIAlertAction * action) { 
      if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){ 
       UIImagePickerController* picker = [[UIImagePickerController alloc] init]; 
       picker.sourceType = UIImagePickerControllerSourceTypeCamera; 
       picker.delegate = self; 
       [self presentViewController:picker animated:YES completion:NULL]; 
                  } 

                 }]; 
UIAlertAction* takeAPicture = 
[UIAlertAction actionWithTitle:@"Choose from gallery" 
         style:UIAlertActionStyleDefault 
         handler:^(UIAlertAction * action) { 
    UIImagePickerController* picker = [[UIImagePickerController alloc] init]; 
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
    picker.delegate = self; 
    [self presentViewController:picker animated:YES completion:NULL]; 
                }]; 
UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" 
        style:UIAlertActionStyleCancel 
        handler:^(UIAlertAction * action) { 
     }]; 

[alertController addAction:pickFromGallery]; 
[alertController addAction:takeAPicture]; 
[alertController addAction:cancel]; 
[self presentViewController:alertController animated:YES completion:nil]; 

}

затем после вы просто поставить UIImagePicker метод делегата, как это:

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info 

{ 
UIImage *imagePicked = info[UIImagePickerControllerOriginalImage]; 
self.imgForUpaloadDocument.image = imagePicked; 
[picker dismissViewControllerAnimated:YES completion:nil]; 

if(picker.sourceType == UIImagePickerControllerSourceTypeCamera) 
{ 
    UIImageWriteToSavedPhotosAlbum(imagePicked, nil, nil, nil); 
} 
} 


-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
    { 
    [picker dismissViewControllerAnimated:YES completion:nil]; 
    } 
0

с выше код, который я хотел бы добавить что-то, что вам может понадобиться для реализации UIImage сборщика ViewController.

Если вы хотите предотвратить сбой приложения, вам необходимо предоставить описание того, почему вы обращаетесь к фотоаппарату, библиотеке фотографий и т. Д. Это новое в iOS10.

Введите следующие данные в файл Info.plist.

Фото

Key: Privacy - Photo Library Использование Описание Стоимость: $ (PRODUCT_NAME) использование фото

камеры

Ключ: Защита - камеры Использование Описание Значение: использование $ (PRODUCT_NAME) камеры

Смежные вопросы