Search code examples
iosswiftuiviewcontrolleruiapplicationuievent

Capturing touches in UIApplication and calling a function in ViewController causing error


I have the below Swift 2 code set up that captures all touches across the whole app. It alerts when touches are occurring and when touches have stopped.

I am wanting to access two functions in another view controller named myVC when touches are occurring and when they’ve stopped, calling function one funcOne() and function two funcTwo(). However I continuously get an error fatal error: unexpectedly found nil while unwrapping an Optional value. It seems whenever myVC is called, it causes errors.

How can I achieve calling a function on the ViewController without errors and please depending on when the app is receiving or not receiving any touch events in Swift 2 please?

main.swift file:

import UIKit

UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))

UIApplication.swift file:

import UIKit

@objc(MyApplication)

class MyApplication: UIApplication {

var myVC: ViewController!

    override func sendEvent(event: UIEvent) {

        if event.type != .Touches {
            super.sendEvent(event)
            return
        }

        var touchesStarted = false
        if let touches = event.allTouches() {
            for touch in touches.enumerate() {
                if touch.element.phase != .Cancelled && touch.element.phase != .Ended {
                    touchesStarted = true
                    break
                }
            }
        }

        if touchesStarted {
    myVC.funcOne()  // Call function one on ViewController
        } else {
    myVC.funcTwo() // Call function two on ViewController
        }

        super.sendEvent(event)
    }
}

Solution

  • The problem is that you are saying

     var myVC: ViewController!
    

    but you are never setting that variable myVC to any value (i.e. an existing ViewController instance). Thus it is always nil, and so when you refer to it in your code, you crash.

    My advice would be that this view controller, in its own viewDidLoad, should say

    (UIApplication.sharedApplication() as MyApplication).myVC = self