Skip to content

Instantly share code, notes, and snippets.

@isma44
Forked from rais38/gist:4683817
Last active September 5, 2015 00:29
Show Gist options
  • Save isma44/64038cc6296ea8becf2d to your computer and use it in GitHub Desktop.
Save isma44/64038cc6296ea8becf2d to your computer and use it in GitHub Desktop.
Embed YouTube videos with UIWebView
#pragma mark - Embed Video
- (UIWebView *)embedVideoYoutubeWithURL:(NSString *)urlString andFrame:(CGRect)frame {
NSString *videoID = [self extractYoutubeVideoID:urlString];
NSString *embedHTML = @"\
<html><head>\
<style type=\"text/css\">\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\"margin:0\">\
<embed id=\"yt\" src=\"http://www.youtube.com/v/%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
NSString *html = [NSString stringWithFormat:embedHTML, videoID, frame.size.width, frame.size.height];
UIWebView *videoWebView = [[UIWebView alloc] initWithFrame:frame];
[videoWebView loadHTMLString:html baseURL:nil];
return videoWebView;
}
/**
@see https://devforums.apple.com/message/705665#705665
extractYoutubeVideoID: works for the following URL formats:
www.youtube.com/v/VIDEOID
www.youtube.com?v=VIDEOID
www.youtube.com/watch?v=WHsHKzYOV2E&feature=youtu.be
www.youtube.com/watch?v=WHsHKzYOV2E
youtu.be/KFPtWedl7wg_U923
www.youtube.com/watch?feature=player_detailpage&v=WHsHKzYOV2E#t=31s
youtube.googleapis.com/v/WHsHKzYOV2E
*/
- (NSString *)extractYoutubeVideoID:(NSString *)urlYoutube {
NSString *regexString = @"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:urlYoutube options:0 range:NSMakeRange(0, [urlYoutube length])];
if(!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
NSString *substringForFirstMatch = [urlYoutube substringWithRange:rangeOfFirstMatch];
return substringForFirstMatch;
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment