我是Swift初学者,刚刚在我的应用程序中完成了我的照相机功能。我现在遇到的问题是,当我从相机拍摄照片时,它不会保存到我的iPhone上的照片库中。一切都很完美,我可以拍照,但是当我查看照片时,似乎没有保存。 我检查了类似的问题,但我没有找到正确的答案,我发现他们是添加按钮直接访问照片库的人,但我不需要这样的按钮。我需要的唯一功能是拍照,当用户点击选择照片将其保存在照片中时。
到目前为止,我已经使用了这个:
class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate{
let imagePicker: UIImagePickerController! = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
let upSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes))
upSwipe.direction = .up
view.addGestureRecognizer(upSwipe)
}
和功能:
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .up){
if ( UIImagePickerController.isSourceTypeAvailable(.camera)){
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
imagePicker.allowsEditing = false
imagePicker.sourceType = .camera
imagePicker.cameraCaptureMode = .photo
present(imagePicker,animated: true, completion: {})
}
}
答案 0 :(得分:6)
在此之前,您需要拥有"隐私 - 照片库添加使用说明"到你的info.plist否则你的应用程序将崩溃
使用此:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
UIImageWriteToSavedPhotosAlbum(pickedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
dismiss(animated: true, completion: nil)
}
}
然后,添加以下函数(与saltTigerK编写的函数相同)
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
来源:https://www.hackingwithswift.com/read/13/5/saving-to-the-ios-photo-library
答案 1 :(得分:1)
快捷键5
无垃圾的透明溶液:
/// Save `image` into Photo Library
UIImageWriteToSavedPhotosAlbum(image, self,
#selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
/// Process photo saving result
@objc func image(_ image: UIImage,
didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
print("ERROR: \(error)")
}
}
别忘了在NSPhotoLibraryAddUsageDescription
中添加Info.plist
键
答案 2 :(得分:0)
...
UIImageWriteToSavedPhotosAlbum(imageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
...
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error == nil {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
} else {
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
您可以在项目中使用此功能
答案 3 :(得分:0)
ViewController类:UIViewController,UINavigationControllerDelegate {
@IBOutlet weak var imageTake: UIImageView!
var imagePicker: UIImagePickerController!
enum ImageSource {
case photoLibrary
case camera
}
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Take image
@IBAction func takePhoto(_ sender: UIButton) {
guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
selectImageFrom(.photoLibrary)
return
}
selectImageFrom(.camera)
}
func selectImageFrom(_ source: ImageSource){
imagePicker = UIImagePickerController()
imagePicker.delegate = self
switch source {
case .camera:
imagePicker.sourceType = .camera
case .photoLibrary:
imagePicker.sourceType = .photoLibrary
}
present(imagePicker, animated: true, completion: nil)
}
//MARK: - Saving Image here
@IBAction func save(_ sender: AnyObject) {
guard let selectedImage = imageTake.image else {
print("Image not found!")
return
}
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
//MARK: - Add image to Library
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
showAlertWith(title: "Save error", message: error.localizedDescription)
} else {
showAlertWith(title: "Saved!", message: "Your image has been saved to your photos.")
}
}
func showAlertWith(title: String, message: String){
let ac = UIAlertController(title: title, message: message, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
扩展ViewController:UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
imagePicker.dismiss(animated: true, completion: nil)
guard let selectedImage = info[.originalImage] as? UIImage else {
print("Image not found!")
return
}
imageTake.image = selectedImage
}
}
答案 4 :(得分:0)
每个应用程序在文档目录中都有其自己的存储。在文档目录中,用户可以存储音频,视频,图像,pdf和其他文件,而不会与其他应用冲突。并且您还可以读写Document目录中特定应用程序的数据。
文档目录将用户数据或文件存储在应用程序路径中。所有文件都存储在特定应用程序的文件夹中。您可以从文档目录的路径读取应用程序数据。
将图像保存在文档目录中:
func saveImageDocumentDirectory(){
让fileManager = NSFileManager.defaultManager()
让路径=(NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as NSString).stringByAppendingPathComponent(“ apple.jpg”)
让图片= UIImage(名称:“ apple.jpg”)
打印(路径)
let imageData = UIImageJPEGRepresentation(image !, 0.5)fileManager.createFileAtPath(路径为String,内容:imageData,属性:nil)
}
获取文档目录路径:
func getDirectoryPath()->字符串{
让路径= NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)
让documentsDirectory =路径[0]返回documentsDirectory
}
从文档目录获取图像:
func getImage(){
让fileManager = NSFileManager.defaultManager()
let imagePAth =(self.getDirectoryPath()as NSString).stringByAppendingPathComponent(“ apple.jpg”)
如果fileManager.fileExistsAtPath(imagePAth){
self.imageView.image = UIImage(contentsOfFile:imagePAth)
}其他{
打印(“无图像”)
}
}
创建目录:
func createDirectory(){
让fileManager = NSFileManager.defaultManager()
让路径=(NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as NSString).stringByAppendingPathComponent(“ customDirectory”)
如果!fileManager.fileExistsAtPath(paths){
尝试! fileManager.createDirectoryAtPath(路径,withIntermediateDirectories:true,属性:nil)
}其他{
print(“已创建字典”。
}
}
删除目录:
func deleteDirectory(){
让fileManager = NSFileManager.defaultManager()
让路径=(NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as NSString).stringByAppendingPathComponent(“ customDirectory”)
如果fileManager.fileExistsAtPath(paths){
尝试! fileManager.removeItemAtPath(paths)
}其他{
print(“有什么事。”)
}
}
答案 5 :(得分:0)
class WethioImageSaver: NSObject {
func writeToPhotoAlbum(image: UIImage) {
let newImagePNG = image.pngData()
let saveableImage = UIImage(data: newImagePNG!)
UIImageWriteToSavedPhotosAlbum(saveableImage!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
print(error)
} else {
print("Sucess")
}
}
}
在将图像保存到照片库之前