来自网址的YouTube视频ID-Swift3 [英] Youtube Video Id from URL - Swift3

查看:112
本文介绍了来自网址的YouTube视频ID-Swift3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个YouTube网址作为字符串,我想从该网址中提取视频ID.我在目标c中找到了一些如下代码:

Basically I have a Youtube URL as string, I want to extract the video Id from that URL. I found some code in objective c that is as below:

NSError *error = NULL;
NSRegularExpression *regex = 
[NSRegularExpression regularExpressionWithPattern:@"?.*v=([^&]+)"
                                          options:NSRegularExpressionCaseInsensitive
                                            error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:youtubeURL
                                                options:0
                                                  range:NSMakeRange(0, [youtubeURL length])];
if (match) {
    NSRange videoIDRange = [match rangeAtIndex:1];
    NSString *substringForFirstMatch = [youtubeURL substringWithRange:videoIDRange];
}

当我将此代码转换为swift3时,即:

When I am converting this code to swift3 that is:

var error: Error? = nil
var regex = try! NSRegularExpression(pattern: "?.*v=([^&]+)", options: .caseInsensitive)
var match = regex!.firstMatch(in: youtubeURL, options: [], range: NSRange(location: 0, length: youtubeURL.length))!
if match {
    var videoIDRange = match.rangeAt(1)
    var substringForFirstMatch = (youtubeURL as NSString).substring(with: videoIDRange)
}

给出错误为:

严重错误:尝试!"表达式意外引发错误:Error Domain = NSCocoaErrorDomain Code = 2048值?.* v =([^&] +)"无效."

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=2048 "The value "?.*v=([^&]+)" is invalid."

有人可以帮助我解决此错误,还是有人可以解释如何在Swift 3中从网址获取视频ID.

Can anybody help me about this error or anybody explain how to get video id from url in Swift 3.

预先感谢

推荐答案

我使用URLComponents的方法与此不同.然后,您可以从网址中选择"v"参数(如果存在).

I have a different way of doing this using URLComponents. You then just select the 'v' parameter from the url, if it exists.

func getYoutubeId(youtubeUrl: String) -> String? {
    return URLComponents(string: youtubeUrl)?.queryItems?.first(where: { $0.name == "v" })?.value
}

然后像这样传递一个Youtube网址:

And then pass in a Youtube url like this:

print (getYoutubeId(youtubeUrl: "https://www.youtube.com/watch?v=Y7ojcTR78qE&spfreload=9"))

这篇关于来自网址的YouTube视频ID-Swift3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆