0

I'm slightly confused as to which way is best to access the settings to enable a device feature if access has been denied before. I have seen two ways which one seems to be using threading. But I haven't found a clear explanation as to why? Would appreciate any insight on this. Thanks.

Both works , either the snippet below as an action of an alert controller:

alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            //open settings to allow access to geo
            guard let stngUrl = URL(string: UIApplicationOpenSettingsURLString) else {
                return
            }
            if UIApplication.shared.canOpenURL(stngUrl) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(stngUrl, completionHandler: { (success) in
                    })
                } else {
                    if UIApplication.shared.canOpenURL(stngUrl) {
                        UIApplication.shared.openURL(stngUrl)
                    }
                }
            }                
        }))
        present(alert, animated: true, completion: nil)

or using DispatchQueue like snippet below?

 alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: {(_ action: UIAlertAction) -> Void in            
        DispatchQueue.main.async(execute: {() -> Void in
            UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
        })
    }))
    present(alert, animated: true, completion: nil)
TheBen
  • 3,410
  • 3
  • 26
  • 51

1 Answers1

0

There is no reason to use DispatchQueue.main in the handler of a UIAlertAction because the handler will always be called on the main thread. So it's redundant to use DispatchQueue.main.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Hi, thanks for the reply, it's interesting what you are saying, so are you saying something like the following is unnecessary? http://stackoverflow.com/a/37420335/5601401 – TheBen Jan 03 '17 at 19:43
  • It shouldn't be needed there, no. – rmaddy Jan 03 '17 at 19:45
  • also, here I see something similar, which confuses me , if handler of UIAlertAction is on main thread why would one need something like this: http://stackoverflow.com/a/31086823/5601401 – TheBen Jan 03 '17 at 19:45
  • What specifically about that are you referring to? – rmaddy Jan 03 '17 at 19:47
  • Sorry I could have been more clear, in first link he uses , NSOperationQueue.mainQueue().addOperationWithBlock and in second he uses, dispatch_async(dispatch_get_main_queue() Now I'm not sure why would one need either and the explanations are not really helping in these links. Thanks – TheBen Jan 03 '17 at 19:56
  • In the first link, there is no need to use the operation queue. In the second, the use of `dispatch_async` is appropriate because of the call to `AVCaptureDevice.requestAccessForMediaType`. The callback will be made on a background queue. – rmaddy Jan 03 '17 at 20:37