사용자가 Swift로 이미지를 선택하도록 허용하는 방법은 무엇입니까?


89

Swift로 첫 번째 iOS 애플리케이션 (iPhone 전용)을 작성하고 있습니다. 메인 애플리케이션보기에서는 사용자가 사진 갤러리에서 이미지를 선택할 수 있어야합니다.

ViewController.swift 의 다음 샘플 코드를 찾았습니다 .

class ViewController: UIImagePickerController, UINavigationControllerDelegate, UIImagePickerControllerDelegate  {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {

        var imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
        imagePickerController.allowsEditing = true
        self.presentViewController(imagePickerController, animated: true, completion: { imageP in

        })
    }


    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
        let selectedImage : UIImage = image
        println(selectedImage)
    }

}

다음과 같은 뷰 컨트롤러 장면이 있습니다.

View Controller
 - Top Layout Guide
 - Bottom Layout Guide
 - View
   - Image View
First Responder
Exit

하지만 앱을 시작하면 검은 색 화면 만 표시됩니다. 내가 뭘 잘못하고 있니? 내가 찾은 또 다른 샘플 코드 는 Objective-C에 있는데 도움이되지 않습니다.


한 가지 문제는 didSselectRowAtIndePath가 UITableViewDelegate에 대한 델리게이트 호출이라는 것입니다. 장면 레이아웃과 코드에 따르면 여기에 사용되는 테이블 뷰가 없으며 ViewController는 UITableViewDelegate가 아닙니다. 아마도 작동하고 버튼을 추가하고 버튼을 눌러 코드를 실행하는 빈 프로젝트를 시작할 것입니다.
Michael Wildermuth 2014 년

@LA_ tableView 함수가 여기에 포함 된 이유를 이해할 수 없습니까?
Dekel Maman 2014-08-26

단지로 이동하여 테스트 잘 작동하고 있어요 : stackoverflow.com/questions/41717115/...
Mr.Javed Multani

그것은이 ALOS을 찾아보세요 theswiftdev.com/...은
Rinto 앤드류스에게

답변:


132

사용자가 UIImagePickerController로 이미지를 선택하게하려면 다음 코드를 사용하십시오.

import UIKit


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var chooseBuuton: UIButton!
    var imagePicker = UIImagePickerController()

    @IBAction func btnClicked() {

        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Button capture")

            imagePicker.delegate = self
            imagePicker.sourceType = .savedPhotosAlbum
            imagePicker.allowsEditing = false

            present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
        self.dismiss(animated: true, completion: { () -> Void in

        })

        imageView.image = image
    }
}

사용자가 버튼을 눌러 이미지를 선택하지 못하도록하려면 어떻게하나요?
LA_

func에서 @IBaction을 제거하고 viewDidLoad에서 말하고 싶을 때마다 func를 호출하거나 언제든지 호출 할 수 있습니다
Dekel Maman

감사. 그것은 말한다 Attempt to present <UIImagePickerController: 0x7fdb84029800> on <MyApp.ViewController: 0x7fdb838360a0> whose view is not in the window hierarchy!. 장면에 무언가를 추가해야합니까?
LA_

3
나는 BC 이것은 정말 도움이되었습니다. NSDictionary를 [NSObject : AnyObject]로 변경하기 만하면 훌륭하게 작동합니다!
scubasteve623 2015

@DekelMaman 리뷰 대기열에 Swift3로 만들기 위해 제안 된 편집이 있었지만 품질이 좋지 않았 으므로 거부하고 더 많은 제안을 피하기 위해 적절한 편집을했습니다
Cœur

80

@ user3182143 답변을 기반으로 신속한 4의 완전한 복사-붙여 넣기 작업 이미지 선택기 :

import Foundation
import UIKit


class ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var picker = UIImagePickerController();
    var alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
    var viewController: UIViewController?
    var pickImageCallback : ((UIImage) -> ())?;
    
    override init(){
        super.init()
        let cameraAction = UIAlertAction(title: "Camera", style: .default){
            UIAlertAction in
            self.openCamera()
        }
        let galleryAction = UIAlertAction(title: "Gallery", style: .default){
            UIAlertAction in
            self.openGallery()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){
            UIAlertAction in
        }

        // Add the actions
        picker.delegate = self
        alert.addAction(cameraAction)
        alert.addAction(galleryAction)
        alert.addAction(cancelAction)
    }

    func pickImage(_ viewController: UIViewController, _ callback: @escaping ((UIImage) -> ())) {
        pickImageCallback = callback;
        self.viewController = viewController;

        alert.popoverPresentationController?.sourceView = self.viewController!.view

        viewController.present(alert, animated: true, completion: nil)
    }
    func openCamera(){
        alert.dismiss(animated: true, completion: nil)
        if(UIImagePickerController .isSourceTypeAvailable(.camera)){
            picker.sourceType = .camera
            self.viewController!.present(picker, animated: true, completion: nil)
        } else {
            let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
            alertWarning.show()
        }
    }
    func openGallery(){
        alert.dismiss(animated: true, completion: nil)
        picker.sourceType = .photoLibrary
        self.viewController!.present(picker, animated: true, completion: nil)
    }

    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    //for swift below 4.2
    //func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    //    picker.dismiss(animated: true, completion: nil)
    //    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    //    pickImageCallback?(image)
    //}
    
    // For Swift 4.2+
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        pickImageCallback?(image)
    }



    @objc func imagePickerController(_ picker: UIImagePickerController, pickedImage: UIImage?) {
    }

}

다음과 같이 viewcontroller에서 호출하십시오.

    ImagePickerManager().pickImage(self){ image in
        //here is the image
    }

또한 다음 키를 포함하는 것을 잊지 마십시오 info.plist.

<key>NSCameraUsageDescription</key>
<string>This app requires access to the camera.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library.</string>

2
func imagePickerController를 이것 으로 대체 해야 작동합니다. 감사! func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage pickImageCallback?(image) picker.dismiss(animated: true, completion: nil) }
Tum

2
'NSInternalInconsistencyException', 이유 : 'UIAlertController는 UIAlertActionStyleCancel 스타일의 작업을 하나만 가질 수 있습니다.'위 코드에서이 오류가 발생합니다.
PaFi

문제를 해결하기 위해 다음 코드를 추가했습니다. if alert.actions.count> 0 {// self.present (alert, animated : true, completed : nil)} else {alert.addAction (cameraAction) alert .addAction (galleryAction) alert.addAction (cancelAction) self.present (alert, animated : true, 완료 : nil)}
Ing. Ron

1
@ Ing.Ron addActions는 한 번만 설정해야하므로 대신 init 메서드에 있어야합니다. 코드를 업데이트했습니다. 문제가 있으면
알려주세요

@vir us : 빠른 응답에 감사드립니다! 제 경우에는 init () 코드를 viewDidLoad ()에 넣어서 잘 작동합니다!
Ing. Ron

39

Swift 3 :

  1. 먼저 info.plist에 다음 키를 추가해야합니다.

        <key>NSPhotoLibraryUsageDescription</key>
    <string>This app requires access to the photo library.</string>
    
  2. View 컨트롤러는 다음 프로토콜을 준수해야합니다. UIImagePickerControllerDelegate, UINavigationControllerDelegate:

    class ImagePickerViewController:  UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
    
  3. 반환 / 선택된 이미지를 바인딩하는 데 사용할 UIImage를 선언해야합니다.

    @IBOutlet weak var myImageView: UIImageView!
    @IBoutlet weak var upLoadImageBtn:UIImage!
    let imagePicker = UIImagePickerController()
    
  4. pickerImage 대리자를 ViewController로 설정하십시오.

    imagePicker.delegate = self
    
  5. 업로드 버튼의 경우 작업을 실행하고 이미지 선택기를 표시하려면 다음 이미지에 연결해야합니다.

    @IBAction func upLoadImageBtnPressed(_ sender: AnyObject) {
        imagePicker.allowsEditing = false
        imagePicker.sourceType = .photoLibrary
    
    
        /*
        The sourceType property wants a value of the enum named        UIImagePickerControllerSourceType, which gives 3 options:
    
        UIImagePickerControllerSourceType.PhotoLibrary
        UIImagePickerControllerSourceType.Camera
        UIImagePickerControllerSourceType.SavedPhotosAlbum
    
        */
        present(imagePicker, animated: true, completion: nil)
    
    }
    
  6. 뷰 컨트롤러는 이미지 선택기 델리게이트에 대한 델리게이트 메서드를 구현해야합니다.

    // MARK: - ImagePicker Delegate
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            myImageView.contentMode = .scaleAspectFit
            myImageView.image = pickedImage
        }
    
    
        /*
    
        Swift Dictionary named “info”.  
        We have to unpack it from there with a key asking for what media information we want.
        We just want the image, so that is what we ask for.  For reference, the available options are:
    
        UIImagePickerControllerMediaType
        UIImagePickerControllerOriginalImage
        UIImagePickerControllerEditedImage
        UIImagePickerControllerCropRect
        UIImagePickerControllerMediaURL
        UIImagePickerControllerReferenceURL
        UIImagePickerControllerMediaMetadata
    
        */
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion:nil)
    }
    

13

이미지를 고르기 위해 가장 이해하기 쉬운 코딩을 드릴 것입니다.

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) 
{
     var alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
     var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
     {
        UIAlertAction in
        self.openCamera()
     }
     var gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
     {
        UIAlertAction in
        self.openGallary()
     }
     var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
     {
        UIAlertAction in
     }

    // Add the actions
     picker?.delegate = self
     alert.addAction(cameraAction)
     alert.addAction(gallaryAction)
     alert.addAction(cancelAction)
     self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera()
{
    if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
    {
        picker!.sourceType = UIImagePickerControllerSourceType.Camera
        self .presentViewController(picker!, animated: true, completion: nil)
    }
    else
    {
        let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
        alertWarning.show()
    }
}
func openGallary()
{
    picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    self.presentViewController(picker!, animated: true, completion: nil)
}

//PickerView Delegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
    picker .dismissViewControllerAnimated(true, completion: nil)
    imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
    println("picker cancel.")
}

좋은 하루 되세요 :-)


8
    @IBAction func chooseProfilePicBtnClicked(sender: AnyObject) {
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
        {
            UIAlertAction in
            self.openCamera()
    }
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
        {
            UIAlertAction in
            self.openGallary()
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
        {
            UIAlertAction in
    }

    // Add the actions
    picker.delegate = self
    alert.addAction(cameraAction)
    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)
    self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera(){
    if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
        picker.sourceType = UIImagePickerControllerSourceType.Camera
        self .presentViewController(picker, animated: true, completion: nil)
    }else{
        let alert = UIAlertView()
        alert.title = "Warning"
        alert.message = "You don't have camera"
        alert.addButtonWithTitle("OK")
        alert.show()
    }
}
func openGallary(){
    picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    self.presentViewController(picker, animated: true, completion: nil)
}
//MARK:UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
    picker .dismissViewControllerAnimated(true, completion: nil)
    imageViewRef.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
    print("picker cancel.")
}

7

Swift 5에서는이 작업을 수행해야합니다.

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func setPicture(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = false

            present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            imageView.image = image
        }

    }




}

5

XCODE 10.1 / SWIFT 4.2 :

  1. 필요한 권한 추가 (기타 언급 됨)

  2. 보기에이 클래스를 추가하십시오.


    import UIKit

    import Photos

    import Foundation

class UploadImageViewController: UIViewController, UIImagePickerControllerDelegate , UINavigationControllerDelegate {

        @IBOutlet weak var imgView: UIImageView!

        let imagePicker = UIImagePickerController()

        override func viewDidLoad() {

            super.viewDidLoad()

            checkPermission()

            imagePicker.delegate = self
            imagePicker.allowsEditing = false
            imagePicker.sourceType = .photoLibrary
        }

        @IBAction func btnSetProfileImageClickedCamera(_ sender: UIButton) {
        }

        @IBAction func btnSetProfileImageClickedFromGallery(_ sender: UIButton) {
            self.selectPhotoFromGallery()
        }

        func selectPhotoFromGallery() {
            self.present(imagePicker, animated: true, completion: nil)
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

            if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                    self.imgView.contentMode = .scaleAspectFit
                    self.imgView.image = pickedImage
                }

            dismiss(animated: true, completion: nil)
        }


        func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
            print("cancel is clicked")
        }


        func checkPermission() {
            let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
            switch photoAuthorizationStatus {
            case .authorized:
                print("Access is granted by user")
            case .notDetermined:
                PHPhotoLibrary.requestAuthorization({
                    (newStatus) in
                    print("status is \(newStatus)")
                    if newStatus ==  PHAuthorizationStatus.authorized {
                        /* do stuff here */
                        print("success")
                    }
                })
                print("It is not determined until now")
            case .restricted:
                // same same
                print("User do not have access to photo album.")
            case .denied:
                // same same
                print("User has denied the permission.")
            }
        }
    }

3

사진 라이브러리 이미지를 신속하게 코딩하려면 다음을 수행하십시오.

var pkcrviewUI = UIImagePickerController()
        if UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            pkcrviewUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            pkcrviewUI.allowsEditing = true
            pkcrviewUI.delegate = self
            [self .presentViewController(pkcrviewUI, animated: true , completion: nil)]
        }

3

이 질문이 1 년 전이라는 것을 알고 있지만 여기 저에게 잘 작동하는 꽤 간단한 코드 (대부분 이 튜토리얼의 코드 )가 있습니다.

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var imagePicker = UIImagePickerController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.imagePicker.delegate = self
}

@IBAction func loadImageButtonTapped(sender: AnyObject) {
    print("hey!")
    self.imagePicker.allowsEditing = false
    self.imagePicker.sourceType = .SavedPhotosAlbum

    self.presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imageView.contentMode = .ScaleAspectFit
        self.imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    self.imagePicker = UIImagePickerController()
    dismissViewControllerAnimated(true, completion: nil)
}

참조하는 하나 개의 I보다 더 깊이 자습서를 찾을 수 있습니다 여기에
레이첼 하비

3

For Swift 4
이 코드는 나를 위해 작동합니다!

import UIKit


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var chooseBuuton: UIButton!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        imagePicker.delegate = self
    }
    @IBAction func btnClicked() {

    if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) 
    {
        print("Button capture")
        imagePicker.sourceType = .savedPhotosAlbum;
        imagePicker.allowsEditing = false

        self.present(imagePicker, animated: true, completion: nil)
        }
    }

  @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    imageView.image = chosenImage

    dismiss(animated: true, completion: nil)
    }
}

2

물론 위의 답변은 주요 문제를 해결합니다.

Info.plist에 다음 플래그가 없기 때문에 사진 앨범을 시작하는 동안 Swift 3.0에서 충돌이 발생했습니다.

  1. 개인 정보-사진 라이브러리 사용 설명-> NSPhotoLibraryUsageDescription

  2. 개인 정보-카메라 사용 설명-> NSCameraUsageDescription

[스크린 샷 [1]

비슷한 문제가 발생하면 추가하십시오.

감사 !


1

다음은이를 수행하는 쉬운 방법입니다.

하지만 먼저 info.plist에 (Privacy-Photo Library Usage Description)을 추가해야하며 viewController에 버튼과 UIImageView가 있어야합니다.

그런 다음 UIImageView의 콘센트 (이 코드에서 콘센트는 myImage라고 함)와 버튼의 동작 (내 코드에서 가져 오기 작업을 호출했습니다)을 만듭니다.

import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    @IBOutlet weak var myImage: UIImageView!
    @IBAction func importing(_ sender: Any) {
        let Picker = UIImagePickerController()
        Picker.delegate = self
        Picker.sourceType = .photoLibrary
        self.present(Picker, animated: true, completion: nil)
        Picker.allowsEditing = true
        Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
    }

     func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])
    {
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1
        myImage.contentMode = .scaleAspectFit //2
        myImage.image = chosenImage //3
        dismiss(animated:true, completion: nil) //4
    }

}

0

별도의 버튼을 원하지 않는 경우 다른 방법이 있습니다. imageView 자체에 제스처를 추가했습니다. 이미지를 탭하면 두 가지 옵션이있는 경고가 표시됩니다. 갤러리 / 사진 라이브러리에서 선택하거나 알림을 취소 할 수있는 옵션이 있습니다.

import UIKit
import CoreData

class AddDetailsViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var picker:UIImagePickerController? = UIImagePickerController()

@IBAction func saveButton(sender: AnyObject) {
    let managedContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext

    let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)

    let person = Person(entity: entity!, insertIntoManagedObjectContext: managedContext)

    person.image = UIImageJPEGRepresentation(imageView.image!, 1.0) //imageView.image

    do {
         try person.managedObjectContext?.save()
         //people.append(person)
       } catch let error as NSError {
         print("Could not save \(error)")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(AddDetailsViewController.tapGesture(_:)))
    imageView.addGestureRecognizer(tapGesture)
    imageView.userInteractionEnabled = true

    picker?.delegate = self
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tapGesture(gesture: UIGestureRecognizer) {
    let alert:UIAlertController = UIAlertController(title: "Profile Picture Options", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

    let gallaryAction = UIAlertAction(title: "Open Gallary", style: UIAlertActionStyle.Default) {
        UIAlertAction in self.openGallary()
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in self.cancel()
    }

    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)

    self.presentViewController(alert, animated: true, completion: nil)

}


func openGallary() {
    picker!.allowsEditing = false
    picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    presentViewController(picker!, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.contentMode = .ScaleAspectFit
        imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)
}

func cancel(){
    print("Cancel Clicked")
}

}

질문에 더 많은 것을 추가하여 CoreData에 이미지를 저장하는 로직을 구현했습니다.


0

버튼을 클릭하고 이미지 갤러리를 열고 imageview swift 3.0에서 이미지를 설정하십시오.

세 위임 UIImagePickerControllerDelegate, UIPopoverControllerDelegate, UINavigationControllerDelegate 추가

var picker:UIImagePickerController?=UIImagePickerController()
@IBOutlet var imgPhoto: UIImageView!

   override func viewDidLoad() {
    super.viewDidLoad()
    picker?.delegate=self
   }

 @IBAction func btnAddPhotoClicked(_ sender: UIButton) {
    openGallary()
   }

func openGallary()
{
    picker!.allowsEditing = false
    picker!.sourceType = UIImagePickerControllerSourceType.photoLibrary
    present(picker!, animated: true, completion: nil)
}

//MARK:- ImagePicker Controller Delegate
//MARK:-

func imagePickerControllerDidCancel(_ picker: 
UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imgPhoto.contentMode = .scaleToFill
        imgPhoto.image = chosenImage
    } else{
        print("Something went wrong")
    }

    self.dismiss(animated: true, completion: nil)
}

0

여기에서 언급하기 만하면됩니다. info[UIImagePickerControllerEditedImage] 대부분의 경우에 사용하고 싶은 것입니다.

그 외에 여기에 대한 답변은 포괄적입니다.


0

UIImagePickerControllerDelegate를 사용하여 이미지를 그리는 것은 쉽습니다.

    @objc func masterAction(_ sender: UIButton)
    {
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Button capture")

            imagePicker.delegate = self
            imagePicker.sourceType = .savedPhotosAlbum;
            imagePicker.allowsEditing = false

            self.present(imagePicker, animated: true, completion: nil)
        }

        print("hello i'm touch \(sender.tag)")
    }

    func imagePickerControllerDidCancel(_ picker:
        UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            print("Get Image \(chosenImage)")
            ImageList.insert(chosenImage, at: 0)
            ArrayList.insert("", at: 0)
            Collection_Vw.reloadData()
        } else{
            print("Something went wrong")
        }

        self.dismiss(animated: true, completion: nil)
    }

0

일반 이미지 만 선택하려면 아래 코드에서 사용할 수 있습니다. 선택한 이미지가 파노라마 이미지가 아닌지 확인하세요.

let picker = UIImagePickerController()

func photoFromLibrary() {

        self.picker.allowsEditing = true
        self.picker.sourceType = .photoLibrary
        //picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!

        self.present(self.picker, animated: true, completion: nil)

}

func shootPhoto() {

            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.picker.allowsEditing = true
                self.picker.sourceType = UIImagePickerControllerSourceType.camera
                self.picker.cameraCaptureMode = .photo
                self.picker.modalPresentationStyle = .fullScreen
                self.present(self.picker,animated: true,completion: nil)
            }

}

//Image picker delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let str = "\(info["UIImagePickerControllerOriginalImage"]!)"

    let s = str.slice(from: "{", to: "}")

    if let arr = s?.components(separatedBy: ","){
        if arr.count >= 2 {
            if Int(arr[0])! > 11000 {
                picker.dismiss(animated:true, completion: nil)
                self.makeToast("Invalid Image!!!")
                return
            }
                     }
        }
    }

    if  let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
        self.UserImageView.image = image
    }
    picker.dismiss(animated:true, completion: nil)
}


func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
    picker.dismiss(animated: true, completion: nil)
}

0

Xcode 10, Swift 4.2

아래는 약간 최적화 된 구현 버전입니다. 이것은 Swift 4.2에 있으며 나도 테스트했습니다.

여기에서 ViewController의 전체 코드를 볼 수 있습니다. IBOutlet (imageView) 및 IBAction (didTapOnChooseImageButton)도 정의하고 스토리 보드에 연결해야합니다. 도움이 되었기를 바랍니다.

import UIKit

class ImagePickViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

var imagePicker = UIImagePickerController()
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func didTapOnChooseImageButton(_ sender: Any) {
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.camera)
    }
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.photoLibrary)
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) {
        UIAlertAction in
    }

    // Add the actions
    imagePicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
    alert.addAction(cameraAction)
    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)
    self.present(alert, animated: true, completion: nil)
}

func openCamera(_ sourceType: UIImagePickerController.SourceType) {
    imagePicker.sourceType = sourceType
    self.present(imagePicker, animated: true, completion: nil)
}

//MARK:UIImagePickerControllerDelegate

func imagePickerController(_ picker: UIImagePickerController,
                                    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    imagePicker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    print("imagePickerController cancel")
}

}

SO Nish에 오신 것을 환영합니다! 코드 전용 답변은 문제가 어떻게 해결되었는지에 대한 통찰력을 제공하지 않기 때문에 권장되지 않습니다. 귀하의 코드가 당면한 문제를 해결하는 방법에 대한 설명을 포함하도록 답변을 업데이트하십시오. :)
Joel

감사합니다, @Joel. 귀하의 제안에 따라 답변을 업데이트했습니다.
Nish

0

여기처럼 할 수 있습니다

var avatarImageView = UIImageView()
var imagePicker = UIImagePickerController()
        
func takePhotoFromGallery() {
    imagePicker.delegate = self
    imagePicker.sourceType = .savedPhotosAlbum
    imagePicker.allowsEditing = true
    
    present(imagePicker, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let pickedImage = info[.originalImage] as? UIImage {
        avatarImageView.contentMode = .scaleAspectFill
        avatarImageView.image = pickedImage
    }
    self.dismiss(animated: true)
}

도움이 되었기를 바랍니다.


-1

Swift 3.4.1의 경우 다음 코드가 작동합니다.

implements                                                             
class AddAdvertisementViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate  

var imagePicker = UIImagePickerController()                                
var file :UIImage!

 //action sheet tap on image

 func tapOnButton(){   
    let optionMenu = UIAlertController(title: nil, message: "Add Photo", preferredStyle: .actionSheet)

    let galleryAction = UIAlertAction(title: "Gallery", style: .default, handler:{
        (alert: UIAlertAction!) -> Void in
        self.addImageOnTapped()
    })

    let cameraAction = UIAlertAction(title: "Camera", style: .default, handler:{
        (alert: UIAlertAction!) -> Void in
        self.openCameraButton()
    })

    let cancleAction = UIAlertAction(title: "Cancel", style: .cancel, handler:{
        (alert: UIAlertAction!) -> Void in
        print("Cancel")
    })

    optionMenu.addAction(galleryAction)
    optionMenu.addAction(cameraAction)
    optionMenu.addAction(cancleAction)
    self.present(optionMenu, animated: true, completion: nil)
}


func openCameraButton(){
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
    {
        imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    }
}


func addImageOnTapped(){
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    }
}

//picker pick image and store value imageview
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    {
            file = image
            imgViewOne.image = image
        imagePicker.dismiss(animated: true, completion: nil);
    }
}

-1
@IBAction func ImportImage(_ sender: Any)
{
    let image = UIImagePickerController()
    image.delegate = self

    image.sourceType = UIImagePickerController.SourceType.photoLibrary

    image.allowsEditing = false

    self.present(image, animated: true)
    {
        //After it is complete
    }


}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    {
        myimage.image = image
    }
    else{
        //
    }
    self.dismiss(animated: true, completion: nil)

    do {
        try context.save()
    } catch {
        print("Could not save. \(error), \(error.localizedDescription)")
    }

}

클래스 정의에 UINavigationControllerDelegate, UIImagePickerControllerDelegate델리게이트 추가


의견을 추가하고, 답변을 설명하고, 답변 방법을 읽으십시오 .
Aksen P
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.