How to get highlighted text range in WebView Content in iOS? - ios

Applied this code in .js file
var selectedText = "";
function getHighlightedString()
{
var text = document.getSelection();
startIndex = text.anchorOffset;
endIndex = text.focusOffset;
selectedText = text.anchorNode.textContent.substr(startIndex,endIndex - text.anchorOffset);
var rangeText = document.getSelection().toString();
}
function highlight() {
if (typeof window.getSelection != "undefined") {
var range = document.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor = "rgb(237,191,245)";
span.style.color = "orange";
range.insertNode(span);
}
}
And I'm using this code for highlighting the text.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"first" ofType:#"js" inDirectory:#""];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[webView_Detail stringByEvaluatingJavaScriptFromString:jsString];
NSString *highlightFunction = [NSString stringWithFormat:#"highlight()"];
[webView_Detail stringByEvaluatingJavaScriptFromString:highlightFunction];
highlightedString = [webView_Detail stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
I stuck for getting the text range. it i have to send to server.but i couldn't able to get selected text range.
Please help me.

Try Following
NSString * strJS = #"window.getSelection().toString()";
NSString * strSelectedText = [self.webView stringByEvaluatingJavaScriptFromString:strJS];
NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString:#"document.body.textContent"];
NSRange * rangeOfString = [plainText rangeOfString:strSelectedText];
You can try following alternate also
NSString *plainText = [self.webView stringByEvaluatingJavaScriptFromString: #"document.body.innerText"];
If there are multiple matches found for selected text, please refer following link to find all ranges of occurrence.
Find all locations of substring in NSString (not just first)

Related

Getting a value from url by using components separated by string

I have a url that looks like this :
https://google.com/image/ghwUT23Y.jpeg
I want to be able to achieve something like this:
section = image;
value = ghwUT23Y;
I have tried to explode the url and usecomponentsSeperatedByStringmethod to grab the values I need.
if ([[explodedUrl firstObject] containsString:#"google.com"] && ![[explodedUrl firstObject] isEqualToString:#"https://google.com/"]) {
NSString *sectionString = [[[explodedUrl lastObject] componentsSeparatedByString:#"/"] firstObject];
NSLog(#"redirectttttt: %#",sectionString);
NSString *itemString = [[[explodedUrl lastObject] componentsSeparatedByString:#"/"] lastObject];
NSLog(#"redirectttttt:2 %#",itemString);
Problem:
Using this method, itemString returns me the value : ghwUT23Y.jpegbut sectionString returns me https://
How would I be able to get image as a section?
You need to convert your string to url first and use the pathComponents method to access each components of that url.
Objective C:
NSURL *url = [NSURL URLWithString:#"ttps://google.com/image/ghwUT23Y.jpeg"];
NSMutableArray *components = [[url pathComponents] mutableCopy];
NSString *fileName = [components lastObject];
[components removeLastObject];
NSString *section = [components lastObject];
NSLog(#"File : %#, Section: %#",fileName, section);
Swift
let url = URL(string: "https://google.com/image/ghwUT23Y.jpeg")
var components = url?.pathComponents
let fileName = components?.popLast()
let section = components?.popLast()
Swift :
func detectUrl() {
let strLongDescription = "https://google.com/image/ghwUT23Y.jpeg"
if(strLongDescription.contains("image")){
var arrString : [String] = strLongDescription.components(separatedBy: "google.com/")
let lastOfarrString : String = arrString.last!
arrString = lastOfarrString.components(separatedBy: "/")
let section = arrString.first!
let value = arrString.last!
}
}

Write Google sheet cell

I try to find how modify or write a cell in a google sheet.
I success to read my sheet (on my drive) with quickstart guide (I had copied and pasted this code : https://developers.google.com/sheets/quickstart/ios#step_3_set_up_the_sample). I had just changed the url by :
https://sheets.googleapis.com/v4/spreadsheets/my_spreadsheet_Id/values/Feuil1!A1:F
.
But impossible to find a code to write on cells of my sheet... when i look : https://developers.google.com/sheets/guides/values#methods. I don't understand where i should put my new data to the cell.
Exemple : i have "New York" on the cell A1.
i want to change "New York" by "Tahiti".
Do you know how do that ?
i tried this but not working :
- (void)modifyListe {
NSString *baseUrl = #"https://sheets.googleapis.com/v4/spreadsheets/";
NSString *spreadsheetId = #"{MySpredsheet_ID}"; // choisir la bonne
NSString *range = #"/values/Feuil1!G1:G1?valueInputOption=Tahiti";
baseUrl = [baseUrl stringByAppendingString:spreadsheetId];
baseUrl = [baseUrl stringByAppendingString:range];
[self.service fetchObjectWithURL:[NSURL URLWithString:baseUrl]
objectClass:[GTLObject class]
delegate:self
didFinishSelector:#selector(displayMajorsWithServiceTicketT:finishedWithObject:error:)];
}
SOLUTION : Look second post
I think found the solution (inspired by this post) :
NSString *baseUrl = #"https://sheets.googleapis.com/v4/spreadsheets/MyspreadsheetID/values/Donnees!G1:G1?valueInputOption=USER_ENTERED";
NSURL *theURL = [NSURL URLWithString:baseUrl];
NSString *rangeKEY = #"range";
NSString *dimensionKEY = #"majorDimension";
NSMutableString *valuesKEY = [NSMutableString stringWithString:#"values"];
NSString *therange = #"Donnees!G1:G1";
NSString *themajorDimension = #"ROWS";
NSMutableString *string_Value = [NSMutableString stringWithString:#"theValue"];
NSMutableArray *ArrayOfString = [NSMutableArray array];
NSMutableArray *arrayOfArray = [NSMutableArray array];
[ArrayOfString addObject:string_Value];
[arrayOfArray addObject:ArrayOfString];
NSMutableDictionary *dicooo = [NSMutableDictionary dictionary];
[dicooo setObject:arrayOfArray forKey:valuesKEY];
[dicooo setObject:therange forKey:rangeKEY];
[dicooo setObject:themajorDimension forKey:dimensionKEY];
GTLObject *theobject ;
theobject = [GTLObject objectWithJSON:dicooo];
[self.service fetchObjectByUpdatingObject:theobject forURL:theURL delegate:self didFinishSelector:#selector(displayMajorsWithServiceTicketT:finishedWithObject:error:)];
When I launch I can see the modification on my sheet.

How to separate NSString with multiple commas?

Am having this nsstring
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
now i want to display only the countries which are suffixed by "en_US".
can anybody tell me how to split that string to get the countries.
I did like this
NSError * error;
NSString* imageName = [[NSBundle mainBundle] pathForResource:#"CountryList" ofType:#"txt"];
NSString * countrStr = [NSString stringWithContentsOfFile:imageName encoding:NSStringEncodingConversionAllowLossy error:&error];
NSArray * dfd = [countrStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<dfd.count;i++)
{
NSString * nama = [dfd objectAtIndex:1];
NSArray * djk = [nama componentsSeparatedByString:#","];
NSString * aksjd = [djk objectAtIndex:1];
}
You can do it like this;
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
NSArray * arrData = [countryStr componentsSeparatedByString:#","];;//[countryStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<arrData.count;i++)
{
NSString * str = [arrData objectAtIndex:i];
if ([str isEqualToString:#"en_US"] && i<arrData.count-1)
{
NSString* countryName = [arrData objectAtIndex:i+1];
NSLog(#"countryName %#", countryName);
}
}
But you should manage data in your file, loading from resource.
Best way to do it is
NSString *string = [NSString stringWithFormat: #"%#, %#, %#", var1, var2, var3];
Excuse the formatting/syntax errors. Typing this via iPhone. But if there is any errors, look up stringWithFormat: in iOS documents on the apple developer page for corrections.
Your string seems to have the following pattern:
A number,
An other number,
The country language code,
The name,
A short code,
An (other) name.
So what you can do is to use a loop like this:
for (int i = 0; i < dfd.count; i += 6) {
if ( dfd[i + 2] ) } // check the country code at index i + 2
// Do something
}
}

Search word or word combinations from text file ios

I am trying to filter words using this code
-(BOOL)isBadWord:(NSString*)string{
NSString* path = [[NSBundle mainBundle] pathForResource:#"wordlist"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSString *delimiter = #"\n";
NSArray *items = [content componentsSeparatedByString:delimiter];
NSString *character = #" ";
NSArray *searchItems = [string componentsSeparatedByString:character];
BOOL isContain = false;
for (int i = 0; i < searchItems.count; i++) {
if (![[searchItems objectAtIndex:i] isEqual:#""]) {
NSUInteger indexOfTheObject =[items containsObject:[searchItems objectAtIndex:i]];
if (indexOfTheObject > 0) {
isContain = true;
}
}
}
return isContain;
}
This is ok for single words, but if combination of words in the text file it not works. eg:
string = word1 {space} word2
What you basically need to do is to iterate an array of bad words/combinations and for each of these steps you should search for this combination on your string like this:
BOOL isContain = NO;
for (NSString *badWord in items) {
if ([string rangeOfString:badWord].location != NSNotFound) {
isContain = YES;
break;
}
}
return isContain;
Please note that BOOL can be YES and NO, but not true and false — it is a special scalar type you should use in Objectve-C when working with Cocoa/CocoaTouch.
Cheers! :)
P.S. it seems you do a lot of work with strings, it may be useful for you to see this String Programming Guide's chapter by Apple.

iOS clickable text inside UITextView

Is there a way to make clickable parts of UITextView. Actually I want to make text something like
By clicking “Register” above, you are agreeing to the Terms of Services and Privacy Statement
where Terms of Services should be one link and Privacy Statement another. And by clicking on those I should do something.
I did it with the code above using this project
- (void)_configureTermsLabel
{
self.termsOfUseLabel.hidden = YES;
self.termsAndConditionsLabel = [[TTTAttributedLabel alloc] initWithFrame:self.termsOfUseLabel.frame];
self.termsAndConditionsLabel.font = [UIFont systemFontOfSize:14];
self.termsAndConditionsLabel.lineBreakMode = UILineBreakModeWordWrap;
self.termsAndConditionsLabel.numberOfLines = 0;
NSString *termsStr = NSLocalizedString(#"Terms of use", #"Terms of use");
NSString *privacyStr = NSLocalizedString(#"Privacy Policy", #"Privacy Policy");
NSString *andStr = NSLocalizedString(#"and", #"and");
NSString *conductStr = NSLocalizedString(#"Code of conduct", #"Code of conduct");
NSString *termsAndConditionsStr = [NSString stringWithFormat:#"%# - %# %# %#", termsStr,
privacyStr, andStr, conductStr];
self.termsAndConditionsLabel.text = termsAndConditionsStr;
NSString *languageCode = [[GLQAppDelegate sharedDelegate] languageIdentifier];
NSURL *termsURL = [NSURL URLWithString:[NSString stringWithFormat:kGLQTermsOfUseURL, languageCode]];
NSURL *privacyURL = [NSURL URLWithString:[NSString stringWithFormat:kGLQPrivacyPolicyURL, languageCode]];
NSURL *conductURL = [NSURL URLWithString:[NSString stringWithFormat:kGLQCodeOfConductURL, languageCode]];
NSRange termsRange = [self.termsAndConditionsLabel.text rangeOfString:termsStr];
NSRange privacyRange = [self.termsAndConditionsLabel.text rangeOfString:privacyStr];
NSRange conductRange = [self.termsAndConditionsLabel.text rangeOfString:conductStr];
[self.termsAndConditionsLabel addLinkToURL:termsURL withRange:termsRange];
[self.termsAndConditionsLabel addLinkToURL:privacyURL withRange:privacyRange];
[self.termsAndConditionsLabel addLinkToURL:conductURL withRange:conductRange];
self.termsAndConditionsLabel.delegate = self;
self.termsAndConditionsLabel.userInteractionEnabled = YES;
[self.scrollView addSubview:self.termsAndConditionsLabel];
}

Resources