Type in String on Website programmatically - html

I'd wanted to know how or whether I can type in something in a textField on a website from my iPhone application code. So I want to go to a website where is one textField in the middle and there I would like to type in a specific string. How can I do that in Swift (or Objective-C - I'll figure out how it works in Swift then)? I would really much appreciate any help :)

You can inject JavaScript into an UIWebView by calling the method stringByEvaluatingJavaScriptFromString. You write a piece of JavaScript where you select the input field and modify it's value attribute.
The method is described here:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/index.html#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString:
There actually is an article on the web that explains how to do just what you need:
http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview/
The following is the part you should use (you just have to change the ID in the DOM selector):
[webView stringByEvaluatingJavaScriptFromString:#"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function myFunction() { "
"var field = document.getElementById('field_3');"
"field.value='Calling function - OK';"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:#"myFunction();"];

You can inject javascript from your delegate. For instance, in Obj-C (I don't know swift good enough yet) :
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[_webView stringByEvaluatingJavaScriptFromString:#"doSomeStuff()"];
}
In your case, you'll want to manipulate the DOM to add some text in your textfield - something like this :
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString * javascript_code = #"document.querySelector('input[name=your_input_name]').value = 'Foobaz'";
[_webView stringByEvaluatingJavaScriptFromString:javascript_code];
}
Beware of querySelector though, I'm not sure about its availability in iOS's webview.

Related

Is it possible to make "HTML to speech" same like "Text to speech"?

I have one weird requirement that in my existing app I have Text2Speech and for that, I have used AVSpeechSynthesizer to speech text, but now the requirement changed and now I need to convert HTML files data to text something like HTML2Speech.
One Solution we can think:
use HTML parsing and get all text from HTML and use same framework
for Text2Speech.
But the client doesn't want that type of parsing and he wants any API or framework which is providing directly HTML2Speech feature.
Any suggestion or help will be highly appreciated.
As I have worked with HTML parsing and text2speech here you can go with 2 steps
1.get Attribute string from HTML file with below code works in iOS7+
As per your client perspective : if there is any API in market for HTML2Speech may be its Paid or
you are depended on that API if you use any. While Native framework
will help same what you/client wants.
Step 1:
[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];
Then you can pass this Attributed String in AVSpeechUtterance
Step 2:
use below method to get HTML2String:
/**
* "ConvertHTMLtoStrAndPlay" : This method will convert the HTML to String
synthesizer.
*
* #param aURLHtmlFilePath : "object of html file path"
*/
-(void)ConvertHTMLtoStrAndPlay:(UIButton*)aBtnPlayPause
isSpeechPaused:(BOOL)speechPaused
stringWithHTMLAttributes:(NSAttributedString*)aStrWithHTMLAttributes
{
if (synthesizer.speaking == NO && speechPaused == NO) {
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:aStrWithHTMLAttributes.string];
//utterance.rate = AVSpeechUtteranceMinimumSpeechRate;
if (IS_ARABIC) {
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:#"ar-au"];
}else{
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:#"en-au"];
}
[synthesizer speakUtterance:utterance];
}
else{
[synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
if (speechPaused == NO) {
[synthesizer continueSpeaking];
} else {
[synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
}
and as usual while you need to stop use below code to stop Speech.
/**
* "StopPlayWithAVSpeechSynthesizer" : this method will stop the playing of audio on the application.
*/
-(void)StopPlayWithAVSpeechSynthesizer{
// Do any additional setup after loading the view, typically from a nib.
[synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
Hope This will help you to get HTML2Speech feature.
There's two parts to a solution here...
Presumably you don't care about the formatting in the HTML--after all, by the time it gets to the speech synthesizer, this text is to be spoken, not viewed. AVSpeechSynthesizer takes plain text, so you just need to get rid of the HTML markup. One easy way to do that is to create an NSAttributedString from the HTML, then ask that attributed string for its underlying plain-text string to pass text to the synthesizer.
In iOS 10 you don't even have to extract the string from an attributed string — you can pass an attributed string directly to AVSpeechUtterance.
One way or another it will always be parsing HTML to something else if you don't want to read files. If the client want direct HTML2Speech solution you can provide a method that takes html file as an argument and read it. What's happening with this file under the hood should not bother client that much as long as it's clean and not causing problems.
What happen when client will ask for Markdown2Speech or XML2Speech. For what i see in your desciption is better to have it for now in one framework with two public methods Text2Speech and HTML2Speech that will take as argument link to file or NSString.
So as #rickster suggest it can be NSAttributedString or NSString. There is a lot of parsers out there, Or if you want own solution you can remove everything what's inside < and > and change encoding.
The safest method will be to extract the text and use existing text2speech API.
Though if you are sure that the browser will be chrome then Speech Synthesis API maybe helpful. But this API still not fully adopted by all browsers; it will be a risky solution.
You can find necessary info regarding this API at
https://developers.google.com/web/updates/2014/01/Web-apps-that-talk-Introduction-to-the-Speech-Synthesis-API?hl=en
https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html#examples-synthesis
https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API
There is no direct API for HTML to Speech except Speech Synthesis API mentioned above. Though you can try http://responsivevoice.org/. But I think this one is also based on browser's Speech Synthesis or Speech generation at server. So to use this one, you would have to extract text and pass the text to API to get the speech

html is not getting rendered after web-view finishes content loading

I have to render html into web-view, In some cases it renders nothing on webview when
-invalid html received from server or html contains flash,.swf and other unsuported media types for iOS.
Webview's webViewDidFinishLoad is getting called in this case also, so I am unable to get this using webview's delegate methods.
To detect these cases I am taking points colors on webview diagonally and when I get alpha 1, it means html render successfully else its a blank.
I am using UIView+ColorOfPoint for getting color at point.
Is there any best way to achieve the same. Please help if you any any better solution.
Thanks
Try to implement following code.
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[webView loadHTMLString:[NSString stringWithFormat:#"%#", error] baseURL:nil];
if (error)
{
// implement your code.
}
}

iOS Associate URL with Saved File

My app parses an xml, and builds its own custom HTML from the contents of the article chosen in the XML. When I save an article, I have a class for the action, in which I pass the article title, and the custom HTML to strings within the Save class. The class takes that and saves it to the app using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[thetitle stringByAppendingString:#".html"]];
NSError *error = nil;
[thehtmlcontents writeToFile:pdfPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
The issue that I have is that if I want to share a saved article via Facebook or Twitter, I can't, because the URL doesn't get saved with everything else. I can pass over the URL easy enough to the Save class, but I'm unsure of what to do with it, so that it stays associated with the article itself. Suggestions?
I'd say you broadly have three options:
Attach some metadata to the file noting the URL it corresponds to
Write out a file format that encapsulates the URL, plus the HTML
Include the URL in the HTML in a manner such that you can retrieve it
no. 1 would probably be best achieved by setting an extended attribute on the file. However, I'm not sure how well iOS supports this, and there may well be issues with it not being preserved in the event of something like restoring the OS.
Are you in a position to implement no. 3 reasonably cleanly? I would say a <meta> tag near the top of the document is best for doing this.
All that said, how important really is it that your HTML is stored in files? To me, this sounds like it could easily be chucked into a dirt simple Core Data database.

How can I pull HTML code into an NSString from an iOS app?

I am trying to pull down the code from an HTML website that has no more than 2 lines on it. The code contains a word that I need to retrieve. Is there a simple way to pull down that code and put it in an NSString?
Further details: I am going to have an app that checks for a word on a page. If that word is what I am looking for, the app will show the text "confirmed". The purpose of the app is to check to see if the page is accessible.
If you need a http library to hit the server try asihttp. Apart from this i need more info of what you are trying to do...
If you just want to check if that website is reachable, you can go with HTTP Success Status Codes.
Using ASIHTTPRequest simplifies communication over the web.
If you still want to evaluate the text on that website, can also just retrieve it using:
[request responseString];
Depending on what you get from the website, it's up to you how to update the UI.
Just change the link between the quotes and it'll work!
-(void) viewDidLoad {
NSString * sFeedURL = [NSString stringWithFormat:#"http://www.google.com/ig/api?weather=,,,270000,960000"];
//RSS Feed URL goes between quotes
NSString * sActualFeed = [NSString stringWithContentsOfURL:[NSURL URLWithString:sFeedURL] encoding:1 error:nil];
NSLog(#"%#", sActualFeed);
}

Opening HTML source code in Cocoa

I'm trying to display HTML source code in my NSDocument based application. However, it renders the page as Safari would show it.
Here's the code that I use to open HTML:
NSData*data;
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSHTMLTextDocumentType
forKey:NSDocumentTypeDocumentOption];
data = [NSData dataWithContentsOfFile:[self fileName]];
mString = [[NSAttributedString alloc]
initWithData:data options:dict documentAttributes:NULL
error:outError];
What am I doing wrong?
The correct solution is a mix of your original code and the bogus solution I gave you in my previous answer (which I've deleted). Use NSPlainTextDocumentType as the type, as you were doing originally, but use initWithData:options:documentAttributes:error:, not initWithHTML:options:documentAttributes:.
Alternatively, create a plain NSString holding the source code, and then create an attributed string with that plain string plus whatever attributes you want to apply to the whole document (e.g., fixed-pitch font).