如何在objective-C中验证youtube网址?

时间:2013-05-16 10:27:39

标签: iphone ios objective-c

我正在尝试验证youtube网址http://www.youtube.com/watch?v=UdQfR4nsXvI。使用下面的代码

(BOOL) validateUrl: (NSString *) candidate
{

NSString *urlRegEx = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";

NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];

return [urlTest evaluateWithObject:candidate];

} 

我还要验证任何youtube网址格式....

编辑代码:


- (IBAction)uplaod_video_Action:(id)sender
{
    NSURL *candidateURL = [NSURL URLWithString:youtube_Url.text];

    // WARNING > "test" is an URL according to RFCs, being just a path
    // so you still should check scheme and all other NSURL attributes you need

    if (candidateURL && candidateURL.scheme && candidateURL.host)
    {
        // candidate is a well-formed url with:
        //  - a scheme (like http://)
        //  - a host (like stackoverflow.com)
        NSLog(@"hallo");
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Please enter the Email" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];

    }

3 个答案:

答案 0 :(得分:3)

使用regexpal.com检查您的验证机制

enter image description here

Raywenderlich.com上有一个非常comprehensive regex tutorial

答案 1 :(得分:0)

试试这个

NSString *urlRegEx = @"(^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$);

答案 2 :(得分:0)

尝试使用此

-(BOOL) validateUrl: (NSString *) candidate
{

NSString *urlRegEx = @"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)";

NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];

return [urlTest evaluateWithObject:candidate];

}