Reputation: 41
I am trying to link an button on the UI to a link that I receive after parsing a JSON response. I've added an outlet to the button with the a variable containing the link.
@IBAction func goOnline(sender: AnyObject) {
UIApplication.sharedApplication().openURL(prodURL)
}
I parse the JSON data in a method called in viewDidLoad.
if let convertedJSONIntoDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject] {
if let JSONurl = convertedJSONIntoDict["url"] as? String {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.prodURL = NSURL(string: JSONurl)!
}
}
}
When I click on the button I don't get any response. As always, any help is much appreciated.
Upvotes: 0
Views: 441
Reputation: 1296
Define your strings and variables and then it's the following code:
@IBAction func websiteButton(_ sender: Any) {
let websiteURL = ("http://") + JSONurl!
guard let url = URL(string: websiteURL) else {
return //be safe
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
That should work.
Upvotes: 0
Reputation: 1199
i dont have enough reputation to comment so i am adding here
what value do you get in json url??? even you dont need to save the value in the main queue you can also write like
self.prodURL = NSURL(string: JSONurl)!
Upvotes: 1