I am passing a Venue object from the PreferencesVC to DiscoverVC by declaring an instance of the class and setting the venue variable to the object being passed.
By the time the code executes beginLoadView() the Venue object is nil and therefore the if statement incorrectly executes
Console output:
Class PreferencesVC: UIViewController{
#IBAction func doneBtnTapped(_ sender: Any) {
print("inside doneBtnTapped selectedVenue.name: \(selectedVenue?.name ?? "selectedVenue is nil")")
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.selectedVenue!
DataService.run.updateUserDiscoveryPreferences(forUID: Auth.auth().currentUser!.uid, discoverableBool: discoverable!, preferences: preferences) { (success) in
self.dismissDetail()
}
}//end func
}
Class DiscoverVC: UIViewController{
var venue: Venue?{
didSet{
print("DiscoverVC venue name: \(venue?.name ?? "venue name")")
}
}
override func viewWillDisappear(_ animated: Bool) {
print("inside viewWillDisappear")
venue = nil
}//end func
override func viewWillAppear(_ animated: Bool) {
print("inside viewWillAppear")
beginLoadView()
}
func beginLoadView(){
print("inside beginLoadView venue.name: \(venue?.name ?? "'venue' is nil")")
if venue != nil {
print("Venue var is not empty venue.name: \(String(describing: venue?.name))")
Utilities.run.showSVHUDWithStatus(uiView: self.view, status: "Discovering")
setupViews()
getCurrentLoggedUserProfile()
showHudAndStartUpdatingLocation()
observeUsersChanges()
} else {
print("Venue var is empty venue.name: \(String(describing: venue?.name))")
Utilities.run.showSVHUDWithStatus(uiView: self.view, status: "Discovering")
fetchNearestVenue()
getCurrentLoggedUserProfile()
}// end if-else
}//end func
}
}
Class VenueDetailsVC: UIViewController{
func presentDiscoverVC(){
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.venue!
discoverVC.showBackButton = true
DispatchQueue.main.async {
self.presentDetail(discoverVC)
}
}//end func
}
As I saw, discoverVC variable is not use to present and discoverVC variable you did set venue is diffirent DiscoverVC object presented. You can try print address of discoverVC and in viewWillAppear.
Related
I was using the code from the following site
https://www.hackingwithswift.com/example-code/media/how-to-scan-a-qr-code
The code works perfectly, the code can be viewed by accessing the link above.
It was a code that capture a QRCode/BarCode from camera and convert it to string.
The part of the the code that shows the string is:
func found(code: String) {
print(code)
}
After that the code string is "printed", the code calls "dismiss" and return to the previous UIViewController.
I want to get the "code" string and get the data to the previous UIViewController.
The only way that I am able to do that now is using the following code:
func found(code: String) {
print("code: \(code)")
ResenhaEquideoIdentificaAnimal1Controller.shared.microchipAnimalTextField.text = code
}
But this code only works if the code is called by the "ResenhaEquideoIdentificaAnimal1Controller" class.
I use the following code to call the new UIViewController inside the "ResenhaEquideoIdentificaAnimal1Controller" class using a UIButton.
let myScannerViewController = MyScannerViewController()
present(myScannerViewController, animated: true, completion: nil)
How can I made this class reusable to be able to call the "MyScannerViewController" class
and send data back to the view that calls it?
You want to use a "delegate patten", that is, when the code is found or something went wrong, you delegate the functionality to some other party to deal with it.
For example, you could modify the existing example to add support for a simple delegate...
import AVFoundation
import UIKit
protocol ScannerDelegate: AnyObject {
func scanner(_ controller: ScannerViewController, didDiscoverCode code: String)
func failedToScanner(_ controller: ScannerViewController)
}
class ScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var captureSession: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
weak var scannerDelegate: ScannerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
captureSession = AVCaptureSession()
guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return }
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch {
return
}
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
} else {
failed()
return
}
let metadataOutput = AVCaptureMetadataOutput()
if (captureSession.canAddOutput(metadataOutput)) {
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
metadataOutput.metadataObjectTypes = [.qr]
} else {
failed()
return
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.layer.bounds
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)
captureSession.startRunning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if (captureSession?.isRunning == false) {
captureSession.startRunning()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if (captureSession?.isRunning == true) {
captureSession.stopRunning()
}
}
private func failed() {
captureSession = nil
scannerDelegate?.failedToScanner(self)
}
private func didFind(code: String) {
scannerDelegate?.scanner(self, didDiscoverCode: code)
}
override var prefersStatusBarHidden: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
captureSession.stopRunning()
if let metadataObject = metadataObjects.first {
guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
guard let stringValue = readableObject.stringValue else { return }
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
didFind(code: stringValue)
}
}
}
When you want to scan something, your calling view controller could adopt the protocol...
extension ViewController: ScannerDelegate {
func failedToScanner(_ controller: ScannerViewController) {
controller.dismiss(animated: true) {
let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
self.present(ac, animated: true)
}
}
func scanner(_ controller: ScannerViewController, didDiscoverCode code: String) {
codeLabel.text = code
controller.dismiss(animated: true)
}
}
and when you wanted to present the scanner view controller, you would simply set the view controller as the delegate...
let controller = ScannerViewController()
controller.scannerDelegate = self
present(controller, animated: true)
The great thing about this is, you could easily reject the code if you weren't interested in simply by modifying the delegate workflow
This is the barcode scanning tutorial I used in my program, so that you have a lot more context when you read my code: Link
Here is what my program does so far: Essentially, when I scan an item's barcode with my phone, the UIAlert pops up with the barcode ID displayed and a button prompting the user to open the "Results" page. This is all fine and good, but how do I pass that same scanned barcode ID into a label on the Result's page? I have been stuck on this for 2 days now, even though it seems like such an easy task.
Any help is much appreciated <3
Here is my relevant code:
ProductCatalog.plist ->
Link to Image
Scanner_ViewController.swift (first View Controller) ->
import UIKit
import AVFoundation
class Scanner_ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate, ScannerDelegate
{
private var scanner: Scanner?
override func viewDidLoad()
{
super.viewDidLoad()
self.scanner = Scanner(withDelegate: self)
guard let scanner = self.scanner else
{
return
}
scanner.requestCaptureSessionStartRunning()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Mark - AVFoundation delegate methods
public func metadataOutput(_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection)
{
guard let scanner = self.scanner else
{
return
}
scanner.metadataOutput(output,
didOutput: metadataObjects,
from: connection)
}
// Mark - Scanner delegate methods
func cameraView() -> UIView
{
return self.view
}
func delegateViewController() -> UIViewController
{
return self
}
func scanCompleted(withCode code: String)
{
print(code)
showAlert_Success(withTitle: (code))
}
private func showAlert_Success(withTitle title: String)
{
let alertController = UIAlertController(title: title, message: "Product has been successfully scanned", preferredStyle: .alert)
// programatically segue to the next view controller when the UIAlert pops up
alertController.addAction(UIAlertAction(title:"Get Results", style: .default, handler:{ action in self.performSegue(withIdentifier: "toAnalysisPage", sender: self) }))
present(alertController, animated: true)
}
}
Scanner.Swift (accompanies Scanner_ViewController.swift)->
import Foundation
import UIKit
import AVFoundation
protocol ScannerDelegate: class
{
func cameraView() -> UIView
func delegateViewController() -> UIViewController
func scanCompleted(withCode code: String)
}
class Scanner: NSObject
{
public weak var delegate: ScannerDelegate?
private var captureSession : AVCaptureSession?
init(withDelegate delegate: ScannerDelegate)
{
self.delegate = delegate
super.init()
self.scannerSetup()
}
private func scannerSetup()
{
guard let captureSession = self.createCaptureSession()
else
{
return
}
self.captureSession = captureSession
guard let delegate = self.delegate
else
{
return
}
let cameraView = delegate.cameraView()
let previewLayer = self.createPreviewLayer(withCaptureSession: captureSession,
view: cameraView)
cameraView.layer.addSublayer(previewLayer)
}
private func createCaptureSession() -> AVCaptureSession?
{
do
{
let captureSession = AVCaptureSession()
guard let captureDevice = AVCaptureDevice.default(for: .video) else
{
return nil
}
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
let metaDataOutput = AVCaptureMetadataOutput()
// add device input
if captureSession.canAddInput(deviceInput) && captureSession.canAddOutput(metaDataOutput)
{
captureSession.addInput(deviceInput)
captureSession.addOutput(metaDataOutput)
guard let delegate = self.delegate,
let viewController = delegate.delegateViewController() as? AVCaptureMetadataOutputObjectsDelegate else
{
return nil
}
metaDataOutput.setMetadataObjectsDelegate(viewController,
queue: DispatchQueue.main)
metaDataOutput.metadataObjectTypes = self.metaObjectTypes()
return captureSession
}
}
catch
{
// handle error
}
return nil
}
private func createPreviewLayer(withCaptureSession captureSession: AVCaptureSession,
view: UIView) -> AVCaptureVideoPreviewLayer
{
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.layer.bounds
previewLayer.videoGravity = .resizeAspectFill
return previewLayer
}
private func metaObjectTypes() -> [AVMetadataObject.ObjectType]
{
return [.qr,
.code128,
.code39,
.code39Mod43,
.code93,
.ean13,
.ean8,
.interleaved2of5,
.itf14,
.pdf417,
.upce
]
}
public func metadataOutput(_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection)
{
self.requestCaptureSessionStopRunning()
guard let metadataObject = metadataObjects.first,
let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject,
let scannedValue = readableObject.stringValue,
let delegate = self.delegate
else
{
return
}
delegate.scanCompleted(withCode: scannedValue)
}
public func requestCaptureSessionStartRunning()
{
self.toggleCaptureSessionRunningState()
}
public func requestCaptureSessionStopRunning()
{
self.toggleCaptureSessionRunningState()
}
private func toggleCaptureSessionRunningState()
{
guard let captureSession = self.captureSession
else
{
return
}
if !captureSession.isRunning
{
captureSession.startRunning()
}
else
{
captureSession.stopRunning()
}
}
}
Analysis_ViewController.swift (second view controller) ->
Right now, the forKey: has been hard-coded to item ID 8710908501708 because I have no idea how to actually pass camera-scanned ID's into the second View Controller :/
import UIKit
class Analysis_ViewController: UIViewController
{
#IBOutlet weak var productTitle: UILabel!
func getData()
{
let path = Bundle.main.path(forResource:"ProductCatalog", ofType: "plist")
let dict:NSDictionary = NSDictionary(contentsOfFile: path!)!
if (dict.object(forKey: "8710908501708" as Any) != nil)
{
if let levelDict:[String : Any] = dict.object(forKey: "8710908501708" as Any) as? [String : Any]
{
// use a for loop to iterate through all the keys and values in side the "Levels" dictionary
for (key, value) in levelDict
{
// if we find a key named whatever we care about, we can print out the value
if (key == "name")
{
productTitle.text = (value as! String)
}
}
}
}
}
// listing the better options that are safer in comparison to the scanned product image
override func viewDidLoad()
{
super.viewDidLoad()
getData()
}
}
Do you have a variable to hold the scanned ID in your view controllers? If not, you can add var itemID: String? to both Scanner_ViewController and Analysis_ViewController.
Then in your func where you get the scanned code, you can set it to the variable.
func scanCompleted(withCode code: String) {
print(code)
itemID = code // Saves the scanned code to your var
showAlert_Success(withTitle: (code))
}
For passing data to another view controller via segue, you might want to look into this UIViewController method for segues: documentation here. This answer also might help.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toAnalysisPage" {
if let viewController = segue.destination as? Analysis_ViewController {
viewController.itemID = itemID
}
}
}
I am building a simple currency converter app. When ViewController gets opened it calls a function from CoinManager.swift:
class ViewController: UIViewController {
var coinManager = CoinManager()
override func viewDidLoad() {
super.viewDidLoad()
coinManager.delegate = self
coinManager.getCoinPrice(for: "AUD", "AZN", firstCall: true)
}
...
}
CoinManager.swift:
protocol CoinManagerDelegate {
func didUpdatePrice(price1: Double, currency1: String, price2: Double, currency2: String)
func tellTableView(descriptions: [String], symbols: [String])
func didFailWithError(error: Error)
}
struct CoinManager {
var delegate: CoinManagerDelegate?
let baseURL = "https://www.cbr-xml-daily.ru/daily_json.js"
func getCoinPrice (for currency1: String,_ currency2: String, firstCall: Bool) {
if let url = URL(string: baseURL) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
self.delegate?.didFailWithError(error: error!)
return
}
if let safeData = data {
if let coinData = self.parseJSON(safeData) {
if firstCall {
var descriptions = [""]
let listOfCoins = Array(coinData.keys)
for key in listOfCoins {
descriptions.append(coinData[key]!.Name)
}
descriptions.removeFirst()
self.delegate?.tellTableView(descriptions: descriptions, symbols: listOfCoins)
}
if let coinInfo1 = coinData[currency1] {
let value1 = coinInfo1.Value
if let coinInfo2 = coinData[currency2] {
let value2 = coinInfo2.Value
//this line does not do anything the second time I call getCoinPrice:
self.delegate?.didUpdatePrice(price1: value1, currency1: currency1, price2: value2, currency2: currency2)
//And this one does work
print("delegate:\(currency1)")
} else {
print("no name matches currency2")
}
} else {
print("no name matches currency1")
}
}
}
}
task.resume()
}
}
func ParseJSON....
}
The method it calls (ViewController.swift):
extension ViewController: CoinManagerDelegate {
func didUpdatePrice(price1: Double, currency1: String, price2: Double, currency2: String) {
print("didUpdatePrice called")
DispatchQueue.main.async {
let price1AsString = String(price1)
let price2AsString = String(price2)
self.leftTextField.text = price1AsString
self.rightTextField.text = price2AsString
self.leftLabel.text = currency1
self.rightLabel.text = currency2
}
}
...
}
and finally, CurrencyViewController.swift:
var coinManager = CoinManager()
#IBAction func backButtonPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
coinManager.getCoinPrice(for: "USD", "AZN", firstCall: false)
}
So when I launch the app i get following in my debug console:
didUpdatePrice called
delegate:AUD
And when I call getCoinPrice() from CurrencyViewController the delegate method does not get called. I know that my code goes through the delegate function line as I get this in debug console:
delegate:USD
I just can't wrap my head around it. The delegate method does not work when gets called second time. Even though it is called by the same algorithm
It's because you're creating a new object of CoinManager in CurrencyViewController where the delegate is not set. So you've to set the delegate every time you create a new instance of CoinManager.
#IBAction func backButtonPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
coinManager.delegate = self
coinManager.getCoinPrice(for: "USD", "AZN", firstCall: false)
}
Update: So, the above solution would require for you to make the delegate conformance in CurrencyViewController. If you're looking for an alternate solution you should probably pass the instance of coinManager in ViewController to CurrencyViewController. For that here are the things you need to update.
In CurrencyViewController:
class CurrencyViewController: UIViewController {
var coinManager: CoinManager! // you can optional unwrap if you intent to use CurrencyViewController without coinManager
//...
And in ViewController:
currencyViewController.coinManager = coinManager // passing the instance of coinManager
Can you share the full code of CoinManager? I see this part
if firstCall {
...
}
Maybe some block logic here or unhandled cases? And can you share the full code of protocol?
Also try to print something before this code:
if error != nil {
self.delegate?.didFailWithError(error: error!)
return
}
I am struggling to address of what I believe to be a State issue between ViewControllers.
The navigation path is as follows;
1.User navigates from VenueDetailsVC to DiscoverVC and passes a Venue object as such:
func presentDiscoverVC(){
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.venue!
discoverVC.showBackButton = true
DispatchQueue.main.async {
self.presentDetail(discoverVC)
}
}
2.User can then navigate from DiscoverVC to PreferencesVC and passes the same Venue object while clearing the local Venue object as such:
class DiscoverVC: UIViewController{
var venue: Venue?{
didSet{
print("DiscoverVC venue name: \(venue?.name ?? "venue name")")
}
}
#IBAction func preferencesBtnTapped(_ sender: Any) {
guard let preferencesVC = storyboard?.instantiateViewController(withIdentifier: "PreferencesVC") as? PreferencesVC else { return }
preferencesVC.selectedVenue = self.venue!
presentDetail(preferencesVC)
}
override func viewWillAppear(_ animated: Bool) {
print("inside viewWillAppear venue: \(venue?.name ?? "venue name")")
}
override func viewWillDisappear(_ animated: Bool) {
venue = nil
}
}
3.User then navigates back to DiscoverVC from PreferencesVC passing the same Venue object
#IBAction func doneBtnTapped(_ sender: Any) {
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.selectedVenue!
DataService.run.updateUserDiscoveryPreferences(forUID: Auth.auth().currentUser!.uid, discoverableBool: discoverable!, preferences: preferences) { (success) in
self.dismissDetail()
}
}
PROBLEM: Is that the Venue object inside the DiscoverVC is nil even though it has been passed back from PreferencesVC on step three above??
Here is the console output:
When you are doing this:
#IBAction func doneBtnTapped(_ sender: Any) {
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.selectedVenue!
You are not setting the venue of the Discover VC that presented the Preferences VC. You are setting the venue of a brand new Discover VC.
You can use the delegate pattern to pass the venue back.
Create a PreferencesVCDelegate:
protocol PreferencesVCDelegate: class {
func preferencesVC(_ vc: PreferencesVC, didDismissWithVenue venue: Venue)
}
Add a delegate property in PreferencesVC:
weak var delegate: PreferencesVCDelegate?
Replace the line that sets venue with a call to the delegate method:
#IBAction func doneBtnTapped(_ sender: Any) {
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
delegate?.preferencesVC(self, didDismissWithVenue: self.venue)
When you present the PreferencesVC, set self as the delegate:
#IBAction func preferencesBtnTapped(_ sender: Any) {
guard let preferencesVC = storyboard?.instantiateViewController(withIdentifier: "PreferencesVC") as? PreferencesVC else { return }
preferencesVC.selectedVenue = self.venue!
preferencesVC.delegate = self
presentDetail(preferencesVC)
}
And conform DiscoverVC to PreferencesVCDelegate. This is where you set discover VC's venue
extension DiscoverVC: PreferencesVCDelegate {
func preferencesVC(_ vc: PreferencesVC, didDismissWithVenue venue: Venue) {
self.venue = venue
}
}
To make an asynchronous request a middleware is used in this case, it returns an error after a fixed amount of time.
The app state is properly updated the subscriber view controller presents the error.
On the next instance however this subscriber view controller is presented, it finds the error in the state - which is actually the error from the previous request and displays the error message before even the request is fired.
How to go about handling this case in ReSwift/Redux?
Store
let store = Store(
reducer: appReducer,
state: AppState(),
middleware: [requestMiddleware]
)
State
struct AppState: StateType {
var isRequestInProgress = false
var result: Result<Bool, NSError>?
}
Actions
struct RequestAction: Action {}
struct ReceiveAction: Action {}
struct ErrorAction: Action {
let error: NSError
}
Middleware
let requestMiddleware: Middleware<Any> = { dispatch, getState in
return { next in
return { action in
switch action {
case is RequestAction:
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
store.dispatch(ErrorAction(error: NSError(domain: "", code: -1, userInfo: nil)))
})
default:
break
}
return next(action)
}
}
}
Reducer
func appReducer(action: Action, state: AppState?) -> AppState {
var state = state ?? AppState()
switch action {
case is RequestAction:
state.isRequestInProgress = true
case let action as ErrorAction:
state.isRequestInProgress = false
state.result = .failure(action.error)
default: break
}
return state
}
The app
class ViewController: UIViewController {
#IBAction func presentControllerB(_ sender: Any) {
guard let viewController = storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") else {
return
}
present(viewController, animated: true)
}
}
class ViewControllerB: UIViewController, StoreSubscriber {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
store.subscribe(self)
}
override func viewWillDisappear(_ animated: Bool) {
store.unsubscribe(self)
super.viewWillDisappear(animated)
}
func newState(state: AppState) {
showActivity(state.isRequestInProgress)
switch state.result {
case .none:
break
case .some(.success(_)):
break
case .some(.failure(let error)):
presentError(error)
dismiss(animated: true)
}
}
#IBAction func request(_ sender: Any) {
store.dispatch(RequestAction())
}
private func showActivity(_ show: Bool) {}
private func presentError(_ error: Error) {
print("Error")
}
}