mvasco
mvasco

Reputation: 5101

Open URL from button action in Swift

In my app I am retrieving an URL from a parse.com Object.

I want to open the device's browser and show the URL received from Parse when the user clicks on the button.

This is the action:

  @IBAction func botonNuevos(sender: AnyObject) {

        let query = PFQuery(className: "datos_contacto")
        query.getObjectInBackgroundWithId("H52ZxGm3U8", block: {
            (questionObject: PFObject?, error: NSError?) -> Void in

            let webNuevos: AnyObject! = questionObject!.valueForKey("dato_contacto")

            print(webNuevos) //= http://www.touchemotors.com

            if let webCallURL = NSURL(string: webNuevos as! String ) {
                let application = UIApplication.sharedApplication()
                if application.canOpenURL(webCallURL) {
                    application.openURL(webCallURL)
                }
                else{
                    print("failed")
                }
            }


        })
    }

when the button is clicked, the log shows the received URL, but the browser is not launched and any error is shown.

Please tell what is wrong in my code. Thank you

Upvotes: 1

Views: 773

Answers (1)

mixel
mixel

Reputation: 25876

UPDATE

Finally after discussion with OP it turned out that value returned by questionObject!.objectForKey("dato_contacto") had whitespace at the end so NSUrl(string:) did not parse it well.

UPDATE

You are using wrong method NSObject.valueForKey(). Use PFObject.objectForKey() instead.

For iOS 9:

From here:

If your app is linked on or after iOS 9.0, you must declare the URL schemes you want to pass to this method. Do this by using the LSApplicationQueriesSchemes array in your Xcode project’s Info.plist file. For each URL scheme you want your app to use with this method, add it as a string in this array.

If your (iOS 9.0 or later) app calls this method using a scheme you have not declared, the method returns false, whether or not an appropriate app for the scheme is installed on the device.

Add http scheme to LSApplicationQueriesSchemes array in Info.plist.

Upvotes: 1

Related Questions