Search code examples
swiftuialertviewqr-codensurlfunc

can't open QR url from an alert view in Swift


I'm trying to open a URL from a QR with Swift, but I can't get with the code to do it. I tried with this func code:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {

    if metadataObjects == nil || metadataObjects.count == 0 {
        vwQRCode?.frame = CGRectZero
        return
    }

    let objMetadataMachineReadableCodeObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

    if objMetadataMachineReadableCodeObject.type == AVMetadataObjectTypeQRCode {
        let objBarCode = objCaptureVideoPreviewLayer?.transformedMetadataObjectForMetadataObject(objMetadataMachineReadableCodeObject as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
        vwQRCode?.frame = objBarCode.bounds;

        if objMetadataMachineReadableCodeObject.stringValue != nil {
            let alert = UIAlertController(title: "Se ha detectado QR", message: objMetadataMachineReadableCodeObject.stringValue, preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Abrir Link", style: UIAlertActionStyle.Default, handler: //nil))

                {action in

                    //UIApplication.sharedApplication().openURL(NSURL(string: "http://www.google.cl")!)
                    UIApplication.sharedApplication().openURL(NSURL(fileURLWithPath: objMetadataMachineReadableCodeObject.stringValue))
            }))

            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

But when I click in the button from the alertView just do nothing. Then I tried with google URL and open with no problem. Please Someone Help me!


Solution

  • Okay. I finally did it. I just change the "fileURLWithPath" for "string"

    Before

    UIApplication.sharedApplication().openURL(NSURL(fileURLWithPath: objMetadataMachineReadableCodeObject.stringValue))
    

    After

    UIApplication.sharedApplication().openURL(NSURL(string: objMetadataMachineReadableCodeObject.stringValue)!)
    

    Now with Swift3 in iOS10 openURL is deprecated, but if you change "openURL" for "open" works perfectly.

    UIApplication.sharedApplication().open(NSURL(string: objMetadataMachineReadableCodeObject.stringValue)!)