在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中重置了视图中的所有内容。一旦我修好了,事情就好了。感谢大家的反馈。希望这有助于其他人不做我做的事。
答案 0 :(得分:1)
根据评论中的请求,我的代码是(a)使用UIImagePickerController从相机胶卷中选择,然后(b)使用UIActivityViewController让用户选择几种可能的方式来将图像保存/附加到多个输出源。
虽然这不是保存到文档目录,但它可能是更好的选择。代码列表后请注意几个注释。
我的"选择"视图控制器,允许用户从相机胶卷中选择或拍照:
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
}
}
}
}
我的"编辑"视图控制器,嵌入在UINavigationBar中,其上的按钮设置为系统项==操作:
// 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 中显示所有评论输出选项。 (我保留这些选项只是为了自我记录。)如果用户有Facebook并希望发布到它,他们将被提示登录,如果他们还没有。