Reputation: 39
I want to create a link, but when pressed it randomly chooses a link from a list. I have the code to take the button a link already, but how how would i modify it so I add more urls to it randomly choose when clicked different times.
Current link code:
@IBAction func Website(_ sender: Any) {
if let url = NSURL(string: "http:heeeeeeeey.com/"){
UIApplication.shared.openURL(url as URL)
}
}
Upvotes: 0
Views: 372
Reputation: 2995
First, to create an array of URL strings is pretty straightforward:
var urls = [
"http://www.url1.com",
"http://www.url2.com",
"http://www.url3.com"
]
Now, you could get a random element of this urls array with this long line of code:
let randomURL = urls[Int(arc4random_uniform(UInt32(urls.count)))]
However, another way you could do it is to add an extension to Array
that works on all arrays:
extension Array {
public var random: Element? {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self.count>0 ? self[index] : nil
}
}
Now, getting a random element of the urls array is as easy as:
urls.random
This returns an Optional
(this is because if there are no elements in an array, the random property will return nil
). So in your code you'll also need to unwrap the result of the random
property:
@IBAction func Website(_ sender: Any) {
if let urlString = urls.random,
let url = URL(string: urlString) {
UIApplication.shared.openURL(url as URL)
}
}
P.S. A couple of comments on your code:
Website
to openRandomWebsite
(remembering to change the storyboard connections too). Methods should explain what they do, and begin with a lower case letter. If you're interested, Swift general code conventions here.Your code would look like:
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
//URL opened
})
Upvotes: 1
Reputation: 276
Try something like:
@IBAction func Website(_ sender: Any) {
let websites = ["http://website1.com",
"http://website2.com",
"http://website3.com"]
if let url = URL(string: websites[Int(arc4random_uniform(UInt32(websites.count)))]) {
UIApplication.shared.openURL(url as URL)
}
}
This should do the trick for you.
Explanation:
websites
is an array of String
s, so put all the URLs you want the button to pick from in there.Int(arc4random_uniform(UInt32(websites.count)))
is the magical part that picks a random number between 0
and websites.count
(which is the last item you have in the array.If you are new to Swift (or programming), this might sound confusing to you, don't freak out, just keep practicing.
Best of luck!
Upvotes: 1