-4

this one is pretty simple I guess but I just can't find the answer that would suit perfectly for my issue. I want to make a button that opens a random URL from a list I'll give him, let's say - google, youtube and facebook just for the example. This is my line of code that connects now only to google...:

- (IBAction)site:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://google.com"]];
}

Can someone please advise me what to add to the code so it will randomly pick these other websites as well?

Tooky
  • 1
  • Have the urls stored in an array then you can use the `rand()` function by passing it the size of the array to get a random number of which you'll use to select the index you want from the array to get your url. Also have a look at using the method `canOpenURL:` in an if statement to make sure you can up it – Popeye Jan 18 '15 at 21:20
  • Thanks @Popeye ! altho i'm kind of a beginner so I didn't really get any of that... :) – Tooky Jan 18 '15 at 21:27
  • Basically what @GustavoBarbosa has put as his answer. – Popeye Jan 18 '15 at 21:29
  • what does this have to do with Xcode? – The Paramagnetic Croissant Jan 19 '15 at 08:17
  • 1
    As a side note: Method names and variables should start with lowercase and Classes and Enums should should with Uppercase I have amended – Popeye Jan 19 '15 at 08:17
  • @TheParamagneticCroissant Since the tag is no longer there as I removed it yesterday it doesn't really matter what they put in there title as long as it is descriptive so it was a wasted edited really, it would have been better if you provided a more descriptive title instead. Though I'm not going to add it back it. – Popeye Jan 19 '15 at 08:18

1 Answers1

1

Like Popeye said, you can store the URLs into a NSArray and pick one of them randomly:

#include <stdlib.h>

- (IBAction)site:(id)sender {
    NSArray *urls = @[
        [NSURL URLWithString:@"http://www.google.com"],
        [NSURL URLWithString:@"http://www.facebook.com"],
        [NSURL URLWithString:@"http://www.twitter.com"]
    ];

    int index = arc4random_uniform(urls.count);
    NSURL *randomURL = urls[index];

    if ([[UIApplication sharedApplication] canOpenURL:randomURL])
        [[UIApplication sharedApplication] openURL:randomURL];
}
Popeye
  • 11,839
  • 9
  • 58
  • 91
Gustavo Barbosa
  • 1,340
  • 1
  • 17
  • 27
  • I was going to provide an answer this morning but there is no point since you already beat me to it by transforming my comment above into an answer +1 – Popeye Jan 19 '15 at 08:15