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에 있는데 도움이되지 않습니다.
답변
사용자가 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
}
}
답변
@ 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>
답변
Swift 3 :
-
먼저 info.plist에 다음 키를 추가해야합니다.
<key>NSPhotoLibraryUsageDescription</key> <string>This app requires access to the photo library.</string>
-
View 컨트롤러는 다음 프로토콜을 준수해야합니다.
UIImagePickerControllerDelegate
,UINavigationControllerDelegate
:class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
-
반환 / 선택된 이미지를 바인딩하는 데 사용할 UIImage를 선언해야합니다.
@IBOutlet weak var myImageView: UIImageView! @IBoutlet weak var upLoadImageBtn:UIImage! let imagePicker = UIImagePickerController()
-
pickerImage 대리자를 ViewController로 설정하십시오.
imagePicker.delegate = self
-
업로드 버튼의 경우 작업을 실행하고 이미지 선택기를 표시하려면 다음 이미지에 연결해야합니다.
@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) }
-
뷰 컨트롤러는 이미지 선택기 델리게이트에 대한 델리게이트 메서드를 구현해야합니다.
// 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) }
답변
이미지를 고르기 위해 가장 이해하기 쉬운 코딩을 드릴 것입니다.
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.")
}
좋은 하루 되세요 🙂
답변
@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.")
}
답변
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
}
}
}
답변
XCODE 10.1 / SWIFT 4.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.")
}
}
}