2016-11-18 42 views
0

我试图在我的应用程序中拍摄一张图像,以便将其保存到我的设备并将其传递到下一个视图控制器以进行预览。我看到人们这样做的方式是将他们拍摄的图像存储在uiimage中。然后在prepareforsegue期间,他们将目标视图控制器中的uiimage变量设置为您在前一个视图控制器中拍摄的照片。从那里在目录视图控制器我看到人们显示图像如下:imageName.image = imageVariable。当我将变量传递给目标视图控制器并尝试在下一个视图控制器中显示它时,它显示为零值。我哪里错了?拍照并将其传递给不同的UIViewController Swift 3.0

第一的ViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "ToDetailPage" { 
     let nextScene = segue.destination as! PostDetailPageViewController 
     nextScene.itemImage = self.image 
     // nextScene?.myimg.image = self.image 
    } 
} 

@IBAction func TakePhotoButtonClicked(_ sender: AnyObject) { 

    if let videoConnection = sessionOutput.connection(withMediaType: AVMediaTypeVideo){ 

     sessionOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { 
     buffer, error in 
      let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) 
      self.image = UIImage(data: imageData!) 
      UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil) 
     }) 

    } 


} 

第二的ViewController:

var itemImage: UIImage! 
@IBOutlet weak var myimg: UIImageView! 

override func viewDidLoad() { 

    super.viewDidLoad() 
    self.categories.dataSource = self; 
    self.categories.delegate = self; 
    setUpMap() 
    myimg.image = itemImage 

} 
+0

'self.image' nonnil在'prepare(for segue:)'中? – Ryan

+0

@瑞安好吧是的,这将解释为什么它没有通过任何价值。它在准备中没有用!任何想法为什么它不存储在takephotobuttonclicked方法的图像? –

+0

在sessionOutput.captureStillImageAsynchronously块呢?有没有错误?块中的'self.image'不是零? – Ryan

回答

1

您需要的viewController推块内。实际上,在prepareForSegue之后,这个代码中发生了什么。所以你的形象总是'零'。

尝试推的viewController是这样的:

if let videoConnection = sessionOutput.connection(withMediaType: AVMediaTypeVideo){ 


sessionOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { 
     buffer, error in 
      let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) 
      self.image = UIImage(data: imageData!) 
      UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil) 
// push view controller here 
let destinationVC = SecondViewController() 
destinationVC.image = self.image 
self.navigationController.pushViewController(destinationVC, animated: true) 
     }) 
} 

希望它会帮助你..快乐编码!

+0

非常感谢你@iProgrammer!由于destinationVC没有值,所以我不得不对代码进行一些更改,但它可以工作!我感谢你的时间。 –

相关问题