How to allow user to pick the image with Swift?

后端 未结 21 804
[愿得一人]
[愿得一人] 2020-12-02 06:01

I am writing my first iOS application (iPhone only) with Swift. The main application view should allow user to choose the image from the photo gallery.

I\'ve found

21条回答
  •  抹茶落季
    2020-12-02 06:33

    If you want to pick only normal image you can use below code,that check that the picked image is not panorama image.

    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)
    }
    

提交回复
热议问题