Random websites button

醉酒当歌 提交于 2019-12-20 07:56:34

问题


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?


回答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];
}


来源:https://stackoverflow.com/questions/28014872/random-websites-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!