gpt4 book ai didi

ios - Swift 3 拍照并保存

转载 作者:行者123 更新时间:2023-11-28 15:59:38 25 4
gpt4 key购买 nike

在 Swift 3 中工作。我发现了很多有答案的问题,还有博客,但我尝试过的一切都没有奏效。我只是想捕捉我拍摄的相机照片并将其保存到文档中。但它没有被保存,因为当从 xcode 中查看时它没有显示在设备文档下,而且我没有收到任何错误或类似错误。我有点迷路了。

获取图片并保存的代码

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var pickedImage = UIImage()
pickedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
picker.dismiss(animated: true, completion: nil)

let currentDateTime = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMddHHmmss"
let fileNameWithExtension = "ts_\(formatter.string(from: currentDateTime)).png"
//create path
let imagePath = fileInDocumentsDirectory(filename: fileNameWithExtension)
imageStringPathSet = fileNameWithExtension
imageSet = pickedImage

if saveImage(image: pickedImage, path: imagePath) {
cameraButton.setImage(#imageLiteral(resourceName: "ic_camerashot_yes60dp"), for: UIControlState.normal)
return
}
cameraButton.setImage(#imageLiteral(resourceName: "ic_camerashot_no60dp"), for: UIControlState.normal)
}
func fileInDocumentsDirectory(filename: String)-> URL {
return try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(filename)
}
func saveImage(image: UIImage, path: URL) -> Bool {
print(path)
guard let pngImageData = UIImagePNGRepresentation(image) else {
print("error")
return false
}

var resultValid = false
do {
let results = try pngImageData.write(to: path, options: [.atomicWrite])
print(results) //prints ()
resultValid = true
}
catch {
resultValid = false
print(error)
}
return resultValid
}

当我打印它打印的路径时

file:///var/mobile/Containers/Data/Application/01EB6A70-34C6-4481-BE5B-7F7AB5E6703F/Documents/ts_20161221145652.png

我认为这是正确的。如果一切正常,它会改变屏幕上的图像,但它永远不会改变,并且 imageStringPathSet 也没有设置,这是一个类变量。任何人都知道我需要做什么才能让它发挥作用?

解决方案

原来原因是我在 viewWillAppear 中重置了 View 中的所有内容。解决此问题后,一切正常。感谢大家的反馈。希望这可以帮助其他人不要做我所做的事情。

最佳答案

根据评论中的要求,这是我的代码,(a) 使用 UIImagePickerController 从相机胶卷中选择,然后 (b) 使用 UIActivityViewController 让用户选择几种可能的方式来保存/附加图像到多个输出源。

虽然这不会保存到文档目录,但它可能是更好的选择。请注意代码 list 后的一些注释。

我的“选择” View Controller ,允许用户从相机胶卷中选择或拍照:

extension SelectViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

// MARK: Camera App

func openCameraApp() {
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.cameraCaptureMode = .photo
picker.modalPresentationStyle = .fullScreen
present(picker,
animated: true,
completion: nil)
} else {
noCamera()
}
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}

// MARK: Photos Albums

func showImagePicker() {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
// picker.modalPresentationStyle = .Popover
present(picker,
animated: true,
completion: nil)
picker.popoverPresentationController?.sourceView = self.view
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
image = chosenImage
self.performSegue(withIdentifier: "ShowEditView", sender: self)
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: false, completion: nil)
}

// MARK: Seque to EditViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowEditView" {
if let vc = segue.destination as? EditViewController {
vc.image = image
}
}
}
}

我的“编辑” View Controller 嵌入在 UINavigationBar 中,上面有一个按钮设置为 System Item == Action:

// MARK: Image actions

@IBAction func shareImage(_ sender: UIBarButtonItem) {
let context = CIContext()
let final = context.createCGImage(imgEdited, from: imgEdited.extent)
let shareImage = UIImage(cgImage: final!)
let vc = UIActivityViewController(activityItems: [shareImage], applicationActivities: [])
vc.excludedActivityTypes = [
//UIActivityTypePostToTwitter,
//UIActivityTypePostToFacebook,
UIActivityType.postToWeibo,
//UIActivityTypeMessage,
//UIActivityTypeMail,
UIActivityType.print,
//UIActivityTypeCopyToPasteboard,
UIActivityType.assignToContact,
//UIActivityTypeSaveToCameraRoll,
UIActivityType.addToReadingList,
//UIActivityTypePostToFlickr,
UIActivityType.postToVimeo,
UIActivityType.postToTencentWeibo
]
present(vc,
animated: true,
completion: nil)
vc.popoverPresentationController?.sourceView = self.view
vc.completionWithItemsHandler = {(activity, success, items, error) in
}
}

注意事项:

  • 请记住,在 iOS 10 设备中使用 UIImagePickerController 时,它崩溃,除非您将它添加到您的 info.plist:

    <key>NSCameraUsageDescription</key>
    <string>Used to capture new image for photo effect</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Used to select an image for photo effect</string>

    您可以在标签中使用您想要的任何内容。

  • UIActivityViewController 将在其excludedActivityTypes 中显示所有已注释 的选项。 (我列出这些选项只是为了 self 记录。)如果用户有 Facebook 并想在上面发帖,如果他们还没有登录,系统会提示他们登录。

关于ios - Swift 3 拍照并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41271943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com