Embed YouTube video not showing on UICollectionView - embed

So another issue I'm having with UICollectionView.
This time I'm trying to show embed videos (YouTube) on a UICollectionViewCell.
The Embed method doesn't work, it gives me blank cells.
If I use the path directly, works, but it will show the whole page on Youtube instead of the video only.
Any idea what could it be?
Here's the code:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
L4VideoCell *videocell = [collectionView dequeueReusableCellWithReuseIdentifier:#"videoCell" forIndexPath:indexPath];
videocell.backgroundColor = [UIColor whiteColor];
NSString *webpath = #"<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/rmx55fxRK5A?rel=0\" frameborder=\"0\" allowfullscreen></iframe>";
[videocell.webAudioView loadHTMLString:webpath baseURL:nil];
return videocell;
}

Ok, found the issue.
I'm not sure if this reason is valid but it worked for me.
Before, I was passing the baseURL:nil. I added my own base URL and it worked.
[webview loadHTMLString:"Embed URL from YouTube" baseURL:[NSURL URLWithString:#"http://www.myurl.com"]];
Hope it helps.

Related

UIWebView ignores inline anchor/link

I'm using a UIWebViewthat loads HTML from a database string using webView.loadHTMLString(self.htmlContent, baseURL: nil)
The htmlContent contains the following:
<ul class="anchorNavigation">
<li>
1. Inline Test Link
</li>
<li>
2. Inline Test Link
</li>
...
</ul>
... and later in the HTML:
...
...
However, whenever I click the inline link in the webView nothing happens.
What I've tried so far:
Changing the anchor tag to 'real' valid W3C HTML. E.g. <a id='parsys_47728'>Test</a>
Saving the HTML to a file in the temp directory and loading it using loadRequest(). E.g. let path = tempDirectory.URLByAppendingPathComponent("content.html") and webView.loadRequest(NSURLRequest(URL: path))
Intercepting the loadRequest method by implementing the func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool delegate. The request.URL says something strange like: "applewebdata://1D9D74C2-BBB4-422F-97A7-554BCCD0055A#parsys_47728"
I don't have any idea anymore how to achieve this. I know from previous projects that local HTML files in the bundle work with inline links. I just cannot figure out why this doesn't work.
Help much appreciated! Thank you!
If there's a fragment (e.g., #anchorName), then use JavaScript to scroll. Otherwise, assume it's a link without a fragment and use openURL.
// UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
// NSLog(#"request.URL %#",request.URL); // e.g., file:///.../myApp.app/#anchorName
NSString *anchorName = request.URL.fragment; // e,g, "anchorName"
if ( anchorName ) {
[webView stringByEvaluatingJavaScriptFromString:[NSString swf:#"window.location.hash='%#';",anchorName]];
return NO;
} else { // assume http://
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
}
return YES;
}
I'm still looking for a way to have the scroll position change smoothly (animated) rather than jumping.

Objective C Using NSScanner to obtain <body> from html

I am trying to create an iOS app simply to extract the section of a web page.
I have the code working to connect to the URL and store the HTML in an NSString
I have tried this, but I am just getting null strings for my result
NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
// Create a new scanner and give it the html data to parse.
while (![newScanner isAtEnd])
{
[newScanner scanUpToString:#"<body>" intoString:NULL];
// Scam until <body> tag is found
[newScanner scanUpToString:#"</body>" intoString:&bodyText];
// Everything up to the end tag will get placed into the memory address of the result string
}
I have tried an alternative way...
NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
// Create a new scanner and give it the html data to parse.
while (![newScanner isAtEnd])
{
[newScanner scanUpToString:#"<body" intoString:NULL];
// Scam until <body> tag is found
[newScanner scanUpToString:#">" intoString:NULL];
// Go to end of opening <body> tag
[newScanner scanUpToString:#"</body>" intoString:&bodyText];
// Everything up to the end tag will get placed into the memory address of the result string
}
This second way returns a string which starts with >< script... etc
If Im honest I don't have a good URL to test this with and I think It may be easier with some help on removing the tags within the body too (like <p></p>)
Any help would be very much appriciated
I don't know why your first method didn't work. I assume you defined bodyText before that snippet. This code worked fine for me,
- (void)viewDidLoad {
[super viewDidLoad];
NSString *htmlData = #"This is some stuff before <body> this is the body </body> with some more stuff";
NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
NSString *bodyText;
while (![newScanner isAtEnd]) {
[newScanner scanUpToString:#"<body>" intoString:NULL];
[newScanner scanString:#"<body>" intoString:NULL];
[newScanner scanUpToString:#"</body>" intoString:&bodyText];
}
NSLog(#"%#",bodyText); // 2015-01-28 15:58:00.360 ScanningOfHTMLProblem[1373:661934] this is the body
}
Notice that I added a call to scanString:intoString: to get past the first "<body>".

Populate a hyperlink attributed string for UIActivityViewController activities

There are lots of answers on SO that show devs how to make a string from HTML content or place a URL in a string, but my question is how to make an HTML string.
I'm trying to create a string that will return in HTML format or at least not show the URL.
So for example web devs would do this to hide the URL:
Visit Us at Google.com!
I can easily translate that to a string by doing so:
NSString *urlLink = #"www.google.com";
NSString *string = [NSString stringWithFormat:#"Visit Us at %#", urlLink];
But that doesn't replace the link with a hyperlink word of my choosing.
I'm aware that the device dictates if its a hyperlink depending on how you display it. i.e., text fields, text views, or you can force open it etc.
What i'm trying to do is:
#define APPSTORELINK #"www.appstorelink.com"
#implementation Config
+(NSString *)appstorelink {
return APPSTORELINK;
}
+(NSString *)mmsmetadata {
NSString *string = [NSString stringWithFormat:#"I shared this publication with the [Name of my iPhone App] iPhone App", APPSTORELINK];
return string;
}
So I can easily call it here or app wide:
NSArray *shareItems;
UIImage *snapshot = [self imageFromView:self.view];
shareItems = #[[Config mmsmetadata], snapshot];
UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:shareItems applicationActivities:nil];
activityController.excludedActivityTypes = #[UIActivityTypePostToFlickr, UIActivityTypeAssignToContact, UIActivityTypeMail, UIActivityTypePostToVimeo];
[activityController setCompletionWithItemsHandler:(UIActivityViewControllerCompletionWithItemsHandler)^(NSString *string, BOOL completed) {
So in short, how can I make the string HTML format out of the box? My main concern is I want to hide the URL and replace it with an HTML tag, or otherwise if you have a better solution. Can't find anything on SO.
Any thoughts? I'm probably overthinking this. I'm sure theres an easier way
EDIT
Before even posting I have been aware of NSAttributedString and that was the first thing I attempted. However, the issue isn't setting an attribute, thats the easy part, the part that is defining my question is how to set it so it will DISPLAY as attributed when using activities in the UIActivityViewController
Here is how I set it, but the outcome was the same as above so I figured it would be easier to use an HTML tag:
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:#"I shared this publication with the Army Pubs iPhone App!"];
NSRange selectedRange = NSMakeRange(0, [string length]);
NSURL *linkURL = [NSURL URLWithString:APPSTORELINK];
[string beginEditing];
[string addAttribute:NSLinkAttributeName
value:linkURL
range:selectedRange];
[string addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor]
range:selectedRange];
[string addAttribute:NSUnderlineStyleAttributeName
value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
range:selectedRange];
[string endEditing];
return string;
However, it still displays as plain text in the Message or Mail composers. So think MFMailComposeViewControllerDelegate how there is a setting for isHTML. If it's set to yes it strips all the HTML tags and displays the text as a hyperlink. For example:
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:YES];
I want to emulate that when the activities are called from within a UIActivityViewController
This is the output currently even if I do it with the attributed string I tried first it just displays as plain text by stripping the HTML tag but doesn't make it a link
See link option in attributed strings.
The link attribute specifies an arbitrary object that is passed to the NSTextView method
clickedOnLink:atIndex: when the user clicks in the text range
associated with the NSLinkAttributeName attribute. The text view’s
delegate object can implement textView:clickedOnLink:atIndex: or
textView:clickedOnLink: to process the link object. Otherwise, the
default implementation checks whether the link object is an NSURL
object and, if so, opens it in the URL’s default application.

How to display html content on UIWebView IOS

I have a form sheet segue that should display hard-coded html page.
Now I have a two part problem first problem is
<CENTER><H1>A Simple Sample Web Page</H1><H4>By Frodo</H4>
<H2>Demonstrating a few HTML features</H2></CENTER>
is displayed like
I can change <CENTER>tag to <left> in that case it works but it limits my options. How can I display this content In the middle of the screen without alignment issues?
Second part of the question is How can I embed a color or a link to content. On line ""FFFFFF">\n" I get the error that says Expected ':' and on line "<a href="http://somegreatsite.com">\n" Half of the line is green which is seems like comment on the screen that means it will not executed by XCode
My full code is like :
- (void) createWebViewWithHTML{
//create the string
NSMutableString *html = [NSMutableString stringWithString: #"<html><head><title></title></head><body style=\"background:transparent;\">"];
//continue building the string
[html appendString:#"<BODY BGCOLOR="
""FFFFFF">\n"
"<CENTER><IMG SRC="clouds.jpg" ALIGN="BOTTOM">
"</CENTER> \n"
"<HR>\n"
"<a href="http://somegreatsite.com">\n"
"Link Name</a>\n"
"is a link to another nifty site\n"
"<H1>This is a Header</H1>\n"
"<H2>This is a Medium Header</H2>\n"
"Send me mail at <a href="mailto:support#yourcompany.com">\n"
"support#yourcompany.com</a>.\n"
"<P> This is a new paragraph!\n"
"<P> <B>This is a new paragraph!</B>\n"
"<BR> <B><I>This is a new sentence without a paragraph break, in bold italics.</I></B>\n"
"<HR>\n"];
[html appendString:#"</body></html>"];
//instantiate the web view
webView = [[UIWebView alloc] initWithFrame:self.view.frame];
//make the background transparent
[webView setBackgroundColor:[UIColor clearColor]];
//pass the string to the webview
[webView loadHTMLString:[html description] baseURL:nil];
//add it to the subview
[self.view addSubview:webView];
}
Edit::
Added story board picture
So how can I make correct alignment and embed color/link correctly?
Check if your UIWebView has the right size. It seems to be bigger than the screen.
Place a \ before any " in your hard-coded string.
e.g.:
NSString *testString="This is a \"Test\"";
results in
This is a "Test"
Hope this helps

UIWebView with contentEditable (html editing), first responder handling?

I'm making an html editor component for an app (using UIWebView with contentEditable in iOS 5.0), and got stuck at how to handle UIWebView first responder status
[webView isFirstResponder], [webView becomeFirstResponder] and [webView resignFirstResponder] don't seem to work, and i've no idea how to make the webView become or resign it by code
If anyone knows how to work this out i would be very grateful, thanks in advance!
Here is how I overwrite these methods in a UIWebView subclass (content is the id of the editable element):
-(BOOL)resignFirstResponder {
[self setUserInteractionEnabled:NO];[self setUserInteractionEnabled:YES];
return [super resignFirstResponder];
}
// only works on iOS 6+
-(void)becomeFirstResponder {
self.keyboardDisplayRequiresUserAction = NO; // set here or during initialization
// important note: in some situations (newer iOS versions), it is also required to first call `blur()` on the 'content' element, otherwise the keyboard won't show up as expected
[self stringByEvaluatingJavaScriptFromString:#"document.getElementById('content').focus()"];
}
-(BOOL)isFirstResponder{
if ([[self stringByEvaluatingJavaScriptFromString:#"document.activeElement.id=='content'"] isEqualToString:#"true"]) {
return YES;
}
else {
return NO;
}
}
isFirstResponder will only return true after the keyboard is shown (e.g, it will return false at UIKeyboardWillShowNotification)
In case this is an issue, another way to check if the UIWebView is the first responder is as follows:
+(BOOL)isFirstResponder:(UIView *)v{
for (UIView *vs in v.subviews) {
if ([vs isFirstResponder] || [self isFirstResponder:vs]) {
return YES;
}
}
return NO;
}
-(BOOL)isFirstResponder{
return [[self class] isFirstResponder:self];
}
This way, the returned value will be YES even before/after the keyboard animation finishes (showing or hiding).
I met the same problem recently, but solved it using pure JavaScript. Actually it doesn't need any Objective-C First Responder related methods. I just used the JavaScript to change the UIWebView's content - the targeting HTML element's contentEditable attribute value according to the requirement.
For example, using the following code to hide the Keyboard that called by the UIWebView's editable content:
[webView stringByEvaluatingJavaScriptFromString:#"document.getElementById('target').setAttribute('contentEditable','false')"];
Hope this is helpful. :)
Here is how I overwrite these methods in a UIWebView subclass (content is the id of the editable element):
[_webView stringByEvaluatingJavaScriptFromString:#"document.getElementById('content').focus()"];
But Focus go to 1st point not last point
Call the following lines of code when you want to hide the keyboard.
//wView is your UIWebView
NSString *webText = [wView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
[wView loadHTMLString:webText baseURL:nil];
[webView loadHTMLString:[NSString stringWithFormat:#"%#", htmlString] baseURL:nil];
This works in iOS > 4