2016-05-08 23 views
0

我有一個非常基本的/簡單的swift應用程序,嵌入WebView通過URL鏈接到Youtube視頻。請參閱下面的完整代碼。我想添加10個其他Youtube URL,並通過一個名爲「shuffleButton」的按鈕在WebView中隨機填充它們。我怎麼能夠非常簡單地使用這個按鈕來加載視頻,然後隨機隨機播放它們。我可以在同一個ViewController中找到視頻URL的主列表嗎?謝謝!隨機隨機清單的URL - 斯威夫特

// ViewController.swift

@IBOutlet var videoView: UIWebView! 

@IBOutlet var shuffleButton: UIButton! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

let youtubeURL = "https://www.youtube.com/embed/Rg6GLVUnnpM" 

    videoView.allowsInlineMediaPlayback = true 

    videoView.loadHTMLString("<iframe width=\"\(videoView.frame.width)\" height=\"\(videoView.frame.height)\" src=\"\(youtubeURL)?&playsinline=1\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil) 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

回答

1

不知道這將是一個非常有效的解決方案,但你可以只創建一個基本的查詢和調用arc4random_uniform(_:)函數產生一個隨機數:

struct VideoLinks { 
    static func getLink(forNumber number: Int) -> String { 
     switch number { 
     case 1: return "http://www.example.com/one" 
     case 2: return "http://www.example.com/two" 
     case 3: return "http://www.example.com/three" 
     case 4: return "http://www.example.com/four" 
     case 5: return "http://www.example.com/five" 
     case 6: return "http://www.example.com/six" 
     case 7: return "http://www.example.com/seven" 
     case 8: return "http://www.example.com/eight" 
     case 9: return "http://www.example.com/nine" 
     case 10: return "http://www.example.com/ten" 
     default: return "http://www.example.com/one" 
     } 
    } 
} 

func shuffle() -> String { 
    let linkNumber = Int(arc4random_uniform(11)) 
    return VideoLinks.getLink(forNumber: linkNumber) 
} 

或者如果你想要一個更簡單的解決方案,只需創建一個鏈接數組並調用一個隨機索引:

let videoLinks = [ 
    "http://www.example.com/1", 
    "http://www.example.com/2", 
    "http://www.example.com/3", 
    "http://www.example.com/4", 
    "http://www.example.com/5", 
    "http://www.example.com/6", 
    "http://www.example.com/7", 
    "http://www.example.com/8", 
    "http://www.example.com/9", 
    "http://www.example.com/10" 
] 

func shuffle() -> String { 
    let randomNumber = Int(arc4random_uniform(10)) 
    return videoLinks[randomNumber] 
} 
0

我可以在同一個ViewController中找到視頻URL的主列表嗎?

當然!

所以讓我們繼續前進,包括在我們的視圖控制器的URL該列表:

let urls = ["URL1", "URL2", "URL3", "URL4"] // etc. 

(這可能被宣佈爲您的視圖控制器內的任何地方,如直接在上面viewDidLoad

現在,我們需要一種方法來選擇一個隨機的URL來打開。這樣做的邏輯方法就是生成一個隨機數組索引。 This question討論了在範圍之間生成隨機數字,this answer是編寫Swift友好方式的好方法。 (如果你選擇跟隨延伸路線,比擴展將需要在全球層面上寫的,任何一類或其他對象之外。)

因此,假如我們定義在上面的答案鏈接描述的randomInt擴展,我們可以得到一個隨機指數,像這樣:

let randomI = Int.random(0..<urls.count) 

因此,我們可以一個IBAction爲增加按下按鈕時會觸發您的視圖控制器。

@IBAction func shuffleURL() { 
    let randomI = Int.random(0..<urls.count) 
    videoView.loadHTMLString(urls[randomI], baseURL: nil) 
} 

注意:如果您的網址數量較少,則可能會導致連續加載相同的網址。