0

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)
        }
    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
H.Sunner
  • 39
  • 6
  • 1
    Why are you using `NSURL` in Swift? Just use `URL`. – rmaddy Apr 08 '17 at 17:43
  • 1
    1) Create an array with all URLs. 2) Read http://stackoverflow.com/questions/24003191/pick-a-random-element-from-an-array. – Martin R Apr 08 '17 at 17:43
  • im sorry to be really dumb, but could you possible help me out on how i would do this. I'm new to swift and need help. – H.Sunner Apr 08 '17 at 17:55

2 Answers2

1

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 Strings, 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!

Marwan Alani
  • 286
  • 1
  • 6
  • Hi, Thank you so much for the help! but i'm getting an error with 'websites.count' saying it cannot covert value of type 'int' to expected argument type 'UInt32'? – H.Sunner Apr 08 '17 at 19:15
  • @H.Sunner My bad, completely forgot about the type mismatch. I fixed the code above, should work fine now. – Marwan Alani Apr 08 '17 at 20:29
1

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:

  • I recommend you rename 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.
  • The openURL method has been deprecated in iOS 10, so I recommend you use the open(_:​options:​completion​Handler:​) method.

Your code would look like:

UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
      //URL opened
    })
Craig Grummitt
  • 2,945
  • 1
  • 22
  • 34
  • Hi, I tried using your method but it errors such as 'cannot use instance member 'ur;' within property initialiser' & the error 'value of type '[String]' has no member 'random'? – H.Sunner Apr 08 '17 at 20:05
  • Did you add the extension `Array` to your code? Are you using Swift 3 / Xcode 8.3? – Craig Grummitt Apr 08 '17 at 20:57