View Controller and displaying another View Controller - ios

I want this.
vc1(performSegue to vc3) -> vc2(For 2 seconds)-dismiss -> vc3
I refer to this.
https://stackoverflow.com/a/39824680/11094223
VC1 CameraViewController
func showVC3() {
performSegue(withIdentifier: "showPhoto_Segue", sender: nil)
}
#IBAction func cameraButton_TouchUpInside(_ sender: Any) {
let settings = AVCapturePhotoSettings()
photoOutput?.capturePhoto(with: settings, delegate: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showLoading_Segue" {
let loadVC = segue.destination as! showLoadingViewController
loadVC.delegate = self
}else if segue.identifier == "showPhoto_Segue" {
let previewVC = segue.destination as! PreviewViewController
previewVC.frameSet = frameSet
previewVC.frameImage = frameImage
previewVC.image = self.image
}
}
extension CameraViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDataRepresentation() {
image = UIImage(data: imageData)
performSegue(withIdentifier: "showLoading_Segue", sender: nil)
}
}
}
vc2 showLoadingViewController
protocol VC2Delegate {
func showVC3()
}
var delegate: VC2Delegate?
override func viewDidLoad() {
super.viewDidLoad()
let time = DispatchTime.now() + .seconds(2)
DispatchQueue.main.asyncAfter(deadline: time) {
self.showPreview()
}
}
func showPreview(){
dismiss(animated: true, completion: nil)
if let _ = delegate {
delegate?.showVC3()
}
}
vc3 PreviewViewController
If you do this
When moving from vc2 to vc3, vc1 comes out for a while, then goes to vc3.
I want to go straight from vc2 to vc3.(dismiss).
not good at English. I'm sorry

The issue that you are having is because you are animating the dismissal of vc2. Just change it to:
dismiss(animated: false, completion: nil)
if let _ = delegate {
delegate?.showVC3()
}
The animation for showVC3 will play as if it was showing over vc2. vc2 meanwhile will disappear from the stack.

Related

Calling Barcodescanner from another class, cant retrieve the data? [duplicate]

I've followed the instructions here but I'm still unsure about this part:
modalVC.delegate=self;
self.presentViewController(modalVC, animated: true, completion: nil)
I've tried instantiating the view controller programmatically but still to no avail.
here's my code for when dismissing the modal view controller:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true) {
//
}
}
I'm using storyboard to segue with modal view.
This is the data I wish to transfer back to the parent view controller:
var typeState = "top"
var categoryState = "casual"
Which are two String values.
I've tried to pass data from the modal view controller as shown:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
delegate?.sendValue(value: "success")
if let presenter = presentingViewController as? OOTDListViewController {
presenter.receivedValue = "test"
}
}
whereas on the parent view controller I did as such:
func sendValue(value: NSString) {
receivedValue = value as String
}
#IBAction func printReceivedValue(_ sender: UIButton) {
print(receivedValue)
}
I still couldnt receive any value when I hit the print button.
Modal view controller:
protocol ModalViewControllerDelegate
{
func sendData(typeState: String, categoryState: String)
}
var delegate:ModalViewControllerDelegate!
var typeState = "top"
var categoryState = "casual"
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
delegate?.sendData(typeState: typeState as String, categoryState: categoryState as String)
}
Parent view controller:
class parentViewController: UICollectionViewController, ModalViewControllerDelegate {
var typeState: String?
var categoryState: String?
func sendData(typeState: String, categoryState: String) {
self.typeState = typeState as String
self.categoryState = categoryState as String
}
#IBAction func printReceivedValue(_ sender: UIButton) {
print(typeState)
}
Here's my new code without using delegate method:
Modal view Controller:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
if let presenter = presentingViewController as? OOTDListViewController {
presenter.typeState = typeState
presenter.categoryState = categoryState
}
}
OOTDListViewController:
#IBAction func presentModalView(_ sender: UIBarButtonItem) {
let modalView = storyboard?.instantiateViewController(withIdentifier: "filterViewController") as! ModalViewController
let navModalView: UINavigationController = UINavigationController(rootViewController: modalView)
self.present(navModalView, animated: true, completion: nil)
}
#IBAction func printValue(_ sender: UIButton) {
print(typeState)
print(categoryState)
}
Depending on the data you want to pass, you can create a property in the presenting view controller, which you can set when dismissing the modal view controller, so you can spare yourself the delegate.
For example, you have a ContactsViewController, holding a var contacts: [Contact] = [] property. When you want to create a new contact, you present a modal view controller with the different values you need to create a new Contact object. When you are done and want to dismiss the view controller, you call the function as you did in your code, but set the property in the ContactsViewController. It will look something like this:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
if let presenter = presentingViewController as? ContactsViewController {
presenter.contacts.append(newContact)
}
dismiss(animated: true, completion: nil)
}
If you don't want to use a delegate, this is how you go about it:
In your OOTDListViewController :
var testValue: String = ""
#IBAction func printReceivedValue(_ sender: UIButton) {
print(testValue)
}
In your modal view controller (I'll call it PresentedViewController) :
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
// if your OOTDListViewController is part of a UINavigationController stack, this check will probably fail.
// you need to put a breakpoint here and check if the presentingViewController is actually a UINavigationController.
// in that case, you will need to access the viewControllers variable and find your OOTDListViewController
if let presenter = presentingViewController as? OOTDListViewController {
presenter.testValue = "Test"
}
dismiss(animated: true, completion: nil)
}
If you want to use a delegate, this is how to do it:
In your OOTDListViewController:
protocol ModalDelegate {
func changeValue(value: String)
}
class OOTDListViewController: ModalDelegate {
var testValue: String = ""
#IBAction func presentViewController() {
// here, you either create a new instance of the ViewController by initializing it, or you instantiate it using a storyboard.
// for simplicity, I'll use the first way
// in any case, you cannot use a storyboard segue directly, bevause you need access to the reference of the presentedViewController object
let presentedVC = PresentedViewController()
presentedVC.delegate = self
present(presentedVC, animated: true, completion: nil)
}
func changeValue(value: String) {
testValue = value
print(testValue)
}
}
In your PresentedViewController:
class PresentedViewController {
var delegate: ModalDelegate?
var testValue: String = ""
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
if let delegate = self.delegate {
delegate.changeValue(testValue)
}
dismiss(animated: true, completion: nil)
}
}
If using a navigation controller you will have to first grab the UINavigation Controller and then get the correct ViewController from the Navigation Controller stack.
Here's how my code looked in that case.
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
if let navController = presentingViewController as? UINavigationController {
let presenter = navController.topViewController as! OOTDListViewController
presenter.testValue = "Test"
}
dismiss(animated: true, completion: nil)
}
I am using the a tab bar so the working code is as below:
if let tabBar = self.presentingViewController as? UITabBarController {
let homeNavigationViewController = tabBar.viewControllers![0] as? UINavigationController
let homeViewController = homeNavigationViewController?.topViewController as! HomeController
homeViewController._transferedLocationID = self.editingLocationID!
}
You need to call the delegate method in dismissViewController method
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
delegate?.sendData(typeState: "top", categoryState: "casual")
self.dismiss(animated: true) {
//
}
}
in you Modal ViewController class create delegate
weak var delegate: MyProtocol?
create a protocol with the method name sendData in MyProtocol and in your presentingViewController where you are assigning the delegate, implement the MyProtocol method
protocol MyProtocol: AnyObject {
func sendData(typeState: String, categoryState: String)
}
class ViewController: UIViewController, MyProtocol {
var typeState: String?
var categoryState: String?
override func viewDidApear() {
super.viewDidApear()
presentNewModalVC()
}
func presentNewModalVC() {
let modalVC = NewModalViewControllerToBePresented()
modalVC.delegate = self
present(modalVC, animated: true)
}
func sendData(typeState: String, categoryState: String) {
self.typeState = typeState
self.categoryState = categoryState
}
}

Why self delegate is nil?

I want to make a weather application by adding a city name with openweathermap api. But I could not send the city I added in AddCityViewController back to HomeViewController. Because, self?.delegate is nil, in AddCityViewController.swift
#objc private func didTapSaveButton() {
print("clicked save button")
if let city = cityTextfield.text {
let weatherURL = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(city)&APPID=b4251cb51691654da529bccf471596bc&units=imperial")!
let weatherResource = Resource<WeatherViewModel>(url: weatherURL) { data in
let weatherVM = try? JSONDecoder().decode(WeatherViewModel.self, from: data)
return weatherVM
}
Webservice().load(resource: weatherResource) { [weak self] result in
if let weatherVM = result {
if let delegate = self?.delegate {
delegate.addWeatherDidSave(vm: weatherVM)
self?.dismiss(animated: true, completion: nil)
}
}
}
}
}
When I debug the prepare function in HomeViewController.swift was not getting called.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nav = segue.destination as? UINavigationController else {
fatalError("NavigationController not found")
}
guard let addWeatherCityVC = nav.viewControllers.first as? AddCityViewController else {
fatalError("AddWeatherCityController not found")
}
addWeatherCityVC.delegate = self
}
What I want is, I want to pass the city name back to HomeViewController when user press the save button.
extension HomeViewController: AddWeatherDelegate {
func addWeatherDidSave(vm: WeatherViewModel) {
print(vm.name)
}
}
Source code in GitHub
You are not using segue for navigation, so the prepareForSegue method won't get triggered. In your code, you are manually initialising an instance of AddCityViewController and presenting it. So to fix the issue, you have to set delegate to that instance.
#objc private func didTapAddButton() {
let vc = AddCityViewController()
vc.title = "Add City"
vc.delegate = self
let nav = UINavigationController(rootViewController: vc)
nav.modalPresentationStyle = .fullScreen
present(nav, animated: true)
}
Or else you can use segue for navigation.

How can I wait until a view controller is done presenting and dismissed to run next line of code? [duplicate]

I've followed the instructions here but I'm still unsure about this part:
modalVC.delegate=self;
self.presentViewController(modalVC, animated: true, completion: nil)
I've tried instantiating the view controller programmatically but still to no avail.
here's my code for when dismissing the modal view controller:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true) {
//
}
}
I'm using storyboard to segue with modal view.
This is the data I wish to transfer back to the parent view controller:
var typeState = "top"
var categoryState = "casual"
Which are two String values.
I've tried to pass data from the modal view controller as shown:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
delegate?.sendValue(value: "success")
if let presenter = presentingViewController as? OOTDListViewController {
presenter.receivedValue = "test"
}
}
whereas on the parent view controller I did as such:
func sendValue(value: NSString) {
receivedValue = value as String
}
#IBAction func printReceivedValue(_ sender: UIButton) {
print(receivedValue)
}
I still couldnt receive any value when I hit the print button.
Modal view controller:
protocol ModalViewControllerDelegate
{
func sendData(typeState: String, categoryState: String)
}
var delegate:ModalViewControllerDelegate!
var typeState = "top"
var categoryState = "casual"
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
delegate?.sendData(typeState: typeState as String, categoryState: categoryState as String)
}
Parent view controller:
class parentViewController: UICollectionViewController, ModalViewControllerDelegate {
var typeState: String?
var categoryState: String?
func sendData(typeState: String, categoryState: String) {
self.typeState = typeState as String
self.categoryState = categoryState as String
}
#IBAction func printReceivedValue(_ sender: UIButton) {
print(typeState)
}
Here's my new code without using delegate method:
Modal view Controller:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
if let presenter = presentingViewController as? OOTDListViewController {
presenter.typeState = typeState
presenter.categoryState = categoryState
}
}
OOTDListViewController:
#IBAction func presentModalView(_ sender: UIBarButtonItem) {
let modalView = storyboard?.instantiateViewController(withIdentifier: "filterViewController") as! ModalViewController
let navModalView: UINavigationController = UINavigationController(rootViewController: modalView)
self.present(navModalView, animated: true, completion: nil)
}
#IBAction func printValue(_ sender: UIButton) {
print(typeState)
print(categoryState)
}
Depending on the data you want to pass, you can create a property in the presenting view controller, which you can set when dismissing the modal view controller, so you can spare yourself the delegate.
For example, you have a ContactsViewController, holding a var contacts: [Contact] = [] property. When you want to create a new contact, you present a modal view controller with the different values you need to create a new Contact object. When you are done and want to dismiss the view controller, you call the function as you did in your code, but set the property in the ContactsViewController. It will look something like this:
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
if let presenter = presentingViewController as? ContactsViewController {
presenter.contacts.append(newContact)
}
dismiss(animated: true, completion: nil)
}
If you don't want to use a delegate, this is how you go about it:
In your OOTDListViewController :
var testValue: String = ""
#IBAction func printReceivedValue(_ sender: UIButton) {
print(testValue)
}
In your modal view controller (I'll call it PresentedViewController) :
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
// if your OOTDListViewController is part of a UINavigationController stack, this check will probably fail.
// you need to put a breakpoint here and check if the presentingViewController is actually a UINavigationController.
// in that case, you will need to access the viewControllers variable and find your OOTDListViewController
if let presenter = presentingViewController as? OOTDListViewController {
presenter.testValue = "Test"
}
dismiss(animated: true, completion: nil)
}
If you want to use a delegate, this is how to do it:
In your OOTDListViewController:
protocol ModalDelegate {
func changeValue(value: String)
}
class OOTDListViewController: ModalDelegate {
var testValue: String = ""
#IBAction func presentViewController() {
// here, you either create a new instance of the ViewController by initializing it, or you instantiate it using a storyboard.
// for simplicity, I'll use the first way
// in any case, you cannot use a storyboard segue directly, bevause you need access to the reference of the presentedViewController object
let presentedVC = PresentedViewController()
presentedVC.delegate = self
present(presentedVC, animated: true, completion: nil)
}
func changeValue(value: String) {
testValue = value
print(testValue)
}
}
In your PresentedViewController:
class PresentedViewController {
var delegate: ModalDelegate?
var testValue: String = ""
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
if let delegate = self.delegate {
delegate.changeValue(testValue)
}
dismiss(animated: true, completion: nil)
}
}
If using a navigation controller you will have to first grab the UINavigation Controller and then get the correct ViewController from the Navigation Controller stack.
Here's how my code looked in that case.
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
if let navController = presentingViewController as? UINavigationController {
let presenter = navController.topViewController as! OOTDListViewController
presenter.testValue = "Test"
}
dismiss(animated: true, completion: nil)
}
I am using the a tab bar so the working code is as below:
if let tabBar = self.presentingViewController as? UITabBarController {
let homeNavigationViewController = tabBar.viewControllers![0] as? UINavigationController
let homeViewController = homeNavigationViewController?.topViewController as! HomeController
homeViewController._transferedLocationID = self.editingLocationID!
}
You need to call the delegate method in dismissViewController method
#IBAction func dismissViewController(_ sender: UIBarButtonItem) {
delegate?.sendData(typeState: "top", categoryState: "casual")
self.dismiss(animated: true) {
//
}
}
in you Modal ViewController class create delegate
weak var delegate: MyProtocol?
create a protocol with the method name sendData in MyProtocol and in your presentingViewController where you are assigning the delegate, implement the MyProtocol method
protocol MyProtocol: AnyObject {
func sendData(typeState: String, categoryState: String)
}
class ViewController: UIViewController, MyProtocol {
var typeState: String?
var categoryState: String?
override func viewDidApear() {
super.viewDidApear()
presentNewModalVC()
}
func presentNewModalVC() {
let modalVC = NewModalViewControllerToBePresented()
modalVC.delegate = self
present(modalVC, animated: true)
}
func sendData(typeState: String, categoryState: String) {
self.typeState = typeState
self.categoryState = categoryState
}
}

How to Segue from a AVPlayer recording to a new Controller?

I have this Delegate in my CameraViewController. It calls fileOutput when its done capturing a video. I want to pass the url of the captured video to my next view controller in my storyboard where I show the captured file:
extension CameraViewController: AVCaptureFileOutputRecordingDelegate{
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
let destinationVC = PreviewViewController()
if (error != nil) {
print("Error recording movie: \(error!.localizedDescription)")
} else {
let videoRecorded = outputURL! as URL
}
outputURL = nil }
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.identifier == "showCapture_Segue" {
let controller = segue.destination as! CameraPreviewController
controller.movieURL = videoRecorded
}
}
}
This is my code right now. There are a lot of complaints from Xcode and it doesn't make sense as Im not passing the videoRecorded from the fileOutput function into the segue override function.
I know to create a segue and pass data into another view controller I do something like
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.identifier == "showCapture_Segue" {
let controller = segue.destination as! CameraPreviewController
controller.movieURL = videoRecorded
}
}
But I'm not sure how this integrates with my AVCaptureFileOutputRecordingDelegate. How can I do this? Thanks!
Edit:
class CameraViewController: UIViewController {
var outputURL: URL!
func startRecording() {
if movieOutput.isRecording == false {
let connection = movieOutput.connection(with: AVMediaType.video)
if (connection?.isVideoOrientationSupported)! {
connection?.videoOrientation = currentVideoOrientation()
}
if (connection?.isVideoStabilizationSupported)! {
connection?.preferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.auto
}
let device = activeInput.device
if (device.isSmoothAutoFocusSupported) {
do {
try device.lockForConfiguration()
device.isSmoothAutoFocusEnabled = false
device.unlockForConfiguration()
} catch {
print("Error setting configuration: \(error)")
}
}
//EDIT2: And I forgot this
outputURL = tempURL()
movieOutput.startRecording(to: outputURL, recordingDelegate: self)
}
else {
stopRecording()
}
}
}
You should declare as instance value
class CameraViewController {
var videoRecorded:URL?
}
//
extension CameraViewController: AVCaptureFileOutputRecordingDelegate{
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
let destinationVC = PreviewViewController()
if (error != nil) {
print("Error recording movie: \(error!.localizedDescription)")
} else {
self.videoRecorded = outputURL as! URL
}
outputURL = nil }
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.identifier == "showCapture_Segue" {
let controller = segue.destination as! CameraPreviewController
controller.movieURL = self.videoRecorded
}
}
}
//
class CameraPreviewController {
var movieURL:URL?
}
//
self.performSegue(withIdentifier: "showCapture_Segue", sender: nil)

Pass data depends on the button in tableView cell

I have a TableView where I display all my data and each cell might have 1-2 buttons. I read many topics and understand how to add target for each button through my ViewController. Since these buttons will be forwarded to the same VC and display images, I have the following code. In my TableViewCell subclass I have 2 buttons
class CODetailsTicketCell: UITableViewCel {
var onButtonTapped: (() -> Void)? = nil
#IBAction func firstBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped()
}
print("First button was pressed")
}
#IBAction func secondBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped()
}
print("Second button was pressed")
}
}
In my ViewController in cellForRowAt indexPath I have the following code
let message = messages[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "COTicketsCell", for: indexPath) as? CODetailsTicketCell {
cell.configureCell(openTickets: message)
cell.onButtonTapped = {
self.performSegue(withIdentifier: "toImageVC", sender: message)
}
return cell
In order to pass the data through segue I use the following code in prepareForSegue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toImageVC" {
let navigationController = segue.destination as? UINavigationController
if let targetController = navigationController?.topViewController as? ImageVC {
if let data = sender as? OpenTicketsData {
targetController.loadImageURL = URL(string: data.firstImageUrl)
}
}
}
}
Everything is working FINE but I can't check for button tag in prepareForSegue. Basically, currently both buttons send the same data
targetController.loadImageURL = URL(string: data.firstImageUrl)
How can I pass data based on the button pressed? I tried to do something like this but seems it's wrong and not working.
let button = sender as? UIButton
if let data = sender as? OpenTicketsData {
if button?.tag == 1 {
targetController.loadImageURL = URL(string: data.firstImageUrl)
} else if button?.tag == 2 {
targetController.loadImageURL = URL(string: data.secondImageUrl)
}
}
You can either separate it into 2 different events or
class CODetailsTicketCell: UITableViewCell {
var onButtonTapped: ((_ sender: UIButton) -> Void)? = nil
#IBAction func firstBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped?(sender)
}
print("First button was pressed")
}
#IBAction func secondBtnTapped(_ sender: UIButton) {
if let onButtonTapped = self.onButtonTapped {
onButtonTapped(sender)
}
print("Second button was pressed")
}
}
In your assignment of the onButtonTapped, remember to add [weak self] if you ever use self to avoid the retain cycle.
cell.onButtonTapped = { [weak self] sender in
if sender.tag == 1 {
// Do something
} else {
// Do other thing
}
}

Resources