I am trying to make a simple iphone program that will allow me to search a keyword when entered into a textfield and then search for it by clicking a rect button. I have searched the site and there is nothing that relates to my current situation. to reiterate, I have a textfield where I would like to enter some text and search for it by clicking a rect button. I have the information i want to search for in a txt file. What is the appropriate way to to go about doing this in xcode for iphone. I appreciate the help, thanks.
If I understand your question correctly, You are trying to find a user defined phrase in a text file.
What you should do is read the file to an NSString, and then search the string for the user defined string.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/SearchingStrings.html
Googled it quickly and found an example (Not written by me!):
NSString *searchFor = #"home";
NSRange range;
for (NSString *string in stringList)
{
range = [word rangeOfString:searchFor];
if (range.location != NSNotFound)
{
NSLog (#"Yay! '%#' found in '%#'.", searchFor, string);
}
}
If I missunderstood you, please update your question so it is better understandable.
Try this:
-(void)searchWord:(NSString *)wordToBeSearched{
NSString* path = [[NSBundle mainBundle] pathForResource:#"wordFile"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSString *delimiter = #"\n";
NSArray *items = [content componentsSeparatedByString:delimiter];
NSString *character = #" ";
BOOL isContain = NO;
for (NSString *wordToBeSearched in items) {
isContain = ([string rangeOfString:wordToBeSearched].location != NSNotFound);
}
return isContain;
}
You can go here for more details
Related
I'm using Youtube API, I'd like to have a search auto-complete feature, just like int the site, when you type into the search input box for iPhone App, it gives you terms suggestions. I've read the docs, but still missing, Is this possible using the API?
Well, i know it's too late to answer here, but i will post this answer because it's something that drove me crazy for a couple of days!!! and hope it will save to others...
So... i'm using this API :
http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&alt=json&q=%#
(q is the query for the autocomplete search).
Now, if you try to open a browser, paste this API and change q=%# to (lets say): q=br, you will notice that some file with the suffix .js is downloaded to your computer.
For some reason, i couldn't parse the JSON like that, so i did that trick:
#property(strong, nonatomic) NSMutableArray *ParsingArray // Put that in .h file or after #interface in your .m file
-(void)autocompleteSegesstions : (NSString *)searchWish{
//searchWish is the text from your search bar (self.searchBar.text)
NSString *jsonString = [NSString stringWithFormat:#"http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&alt=json&q=%#", searchWish];
NSString *URLString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // Encoding to identify where, for example, there are spaces in your query.
NSLog(#"%#", URLString);
NSData *allVideosData = [[NSData alloc]initWithContentsOfURL:[[NSURL alloc]initWithString:URLString]];
NSString *str = [[NSString alloc]initWithData:allVideosData encoding:NSUTF8StringEncoding];
NSLog(#"%#", str); //Now you have NSString contain JSON.
NSString *json = nil;
NSScanner *scanner = [NSScanner scannerWithString:str];
[scanner scanUpToString:#"[[" intoString:NULL]; // Scan to where the JSON begins
[scanner scanUpToString:#"]]" intoString:&json];
//The idea is to identify where the "real" JSON begins and ends.
json = [NSString stringWithFormat:#"%#%#", json, #"]]"];
NSLog(#"json = %#", json);
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] //Push all the JSON autocomplete detail in to jsonObject array.
options:0 error:NULL];
self.ParsingArray = [[NSMutableArray alloc]init]; //array that contains the objects.
for (int i=0; i != [jsonObject count]; i++) {
for (int j=0; j != 1; j++) {
NSLog(#"%#", [[jsonObject objectAtIndex:i] objectAtIndex:j]);
[self.ParsingArray addObject:[[jsonObject objectAtIndex:i] objectAtIndex:j]];
//Parse the JSON here...
}
}}
That's it. now ParsingArray is the array that contains all autocomplete information from youTube! to be able to change it every time the user clicks another character on the searchBar, use this function:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[self autocompleteSegesstions:self.searchBar.text];}
Now, this is the main code you should have. to make this code faster (because you can now see that you have a writing delay on the keyboard), use another thread to download ParsingArray or use Asynchronous block. (just insert the content of the first method to Async block...)
Remember- maybe there is another way to implement autocomplete youTube search much better then this, but i just did not found it, and i searched a lot! if anyone know a better way, i'll be more then glad if he post it here.
Have fun!!!
Not the Youtube API -- but you can use the Google Suggest API. Make calls to this URL:
http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=QUERY
Which will return a json response of the suggest terms that your app can parse and display. If you prefer XML to json, change
client=youtube
to
output=toolbar
(leave the rest of the parameters the same).
I am showing a web page using html string in a UIWebview. I want to retrieve the value typed from the below text area code.
result = [result stringByAppendingFormat:#"<textarea name=\"qId_"];
NSString *questionid = [question valueForKey:#"QuestionId"];
NSString *questionidSTR = (NSString *) [NSString stringWithFormat:#"%#", questionid];
result = [result stringByAppendingFormat:questionidSTR];
[questionidArray addObject:questionidSTR];
result = [result stringByAppendingFormat:#"\" rows=\"5\" style=\"width:90%\"></textarea>"];
I tried
NSString *value = [NSString stringWithFormat:#"%#%#%#",#"document.getElementById('",[questionidArray objectAtIndex:i],#"').value"];
NSString* out = [enterSurveyWebview stringByEvaluatingJavaScriptFromString:value];
But, its not giving the correct output, i think i'm doing wrong when retrieving the value.
Could someone please correct me for retrieving portion?
Thank you.
Your <textarea> has a name of qId_%# (where %# is the QuestionId), but your javascript is only asking for %#. You also need to be using getElementByName() instead of getElementById().
NSString *value = [NSString stringWithFormat:#"document.getElementsByName('qId_%#')[0].value", [questionidArray objectAtIndex:i]];
I have an NSMutable dictionary that contains file IDs and their filename+extension in the simple form of fileone.doc or filetwo.pdf. I need to determine what type of file it is to correctly display a related icon in my UITableView. Here is what I have done so far.
NSString *docInfo = [NSString stringWithFormat:#"%d", indexPath.row]; //Determine what cell we are formatting
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string
I wrote two regex to determine what type of file I'm looking at, but they never return a positive result. I haven't used regex in iOS programming before, so I'm not entirely sure if I'm doing it right, but I basically copied the code from the Class Description page.
NSError *error = NULL;
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])];
NSLog(#"How many matches were found? %#", numMatch);
My questions would be, is there an easier way to do this? If not, are my regex incorrect? And finally if I have to use this, is it costly in run time? I don't know what the average amount of files a user will have will be.
Thank you.
You're looking for [fileType pathExtension]
NSString Documentation: pathExtension
//NSURL *url = [NSURL URLWithString: fileType];
NSLog(#"extension: %#", [fileType pathExtension]);
Edit you can use pathExtension on NSString
Thanks to David Barry
Try this :
NSString *fileName = #"resume.doc";
NSString *ext = [fileName pathExtension];
Try this, it works for me.
NSString *fileName = #"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
Documentation here for NSString pathExtension
Try using [fileType pathExtension] to get the extension of the file.
In Swift 3 you could use an extension:
extension String {
public func getExtension() -> String? {
let ext = (self as NSString).pathExtension
if ext.isEmpty {
return nil
}
return ext
}
}
I have a text with http:// in NSString. I want to get that http link from the NSString. How can i get the link/url from the string? Eg: 'Stack over flow is very useful link for the beginners https://stackoverflow.com/'. I want to get the 'https://stackoverflow.com/' from the text. How can i do this? Thanks in advance.
I am not sure what you exactly mean by link but if you want to convert your NSString to NSURL than you can do the following:
NSString *urlString = #"http://somepage.com";
NSURL *url = [NSURL URLWithString:urlString];
EDIT
This is how to get all URLs in a given NSString:
NSString *str = #"This is a grate website http://xxx.xxx/xxx you must check it out";
NSArray *arrString = [str componentsSeparatedByString:#" "];
for(int i=0; i<arrString.count;i++){
if([[arrString objectAtIndex:i] rangeOfString:#"http://"].location != NSNotFound)
NSLog(#"%#", [arrString objectAtIndex:i]);
}
Rather than splitting the string into an array and messing about that way, you can just search for the substring beginning with #"http://":
NSString *str = #"Stack over flow is very useful link for the beginners http://stackoverflow.com/";
// get the range of the substring starting with #"http://"
NSRange rng = [str rangeOfString:#"http://" options:NSCaseInsensitiveSearch];
// Set up the NSURL variable to hold the created URL
NSURL *newURL = nil;
// Make sure that we actually have found the substring
if (rng.location == NSNotFound) {
NSLog(#"URL not found");
// newURL is initialised to nil already so nothing more to do.
} else {
// Get the substring from the start of the found substring to the end.
NSString *urlString = [str substringFromIndex:rng.location];
// Turn the string into an URL and put it into the declared variable
newURL = [NSURL URLWithString:urlString];
}
try this :
nsstring *str = #"Stack over flow is very useful link for the beginners http://stackoverflow.com/";
nsstring *http = #"http";
nsarray *arrURL = [str componentsSeparatedByString:#"http"];
this will give two objects in the nsarray. 1st object will be having:Stack over flow is very useful link for the beginners and 2nd will be : ://stackoverflow.com/ (i guess)
then you can do like:
NSString *u = [arrURL lastObject];
then do like:
nsstring *http = [http stringByAppendingFormat:#"%#",u];
Quite a lengthy,but i think that would work for you. Hope that helps you.
I have a txt file with some URLs like this
http://url1.com
http://url1.com
http://url1.com
Separated by a line break. How could I add those as different entries separated by line breaks to an NSMutableArray? Thanks :)
Try something like this:
NSMutableArray *txtLines = [NSMutableArray array];
[txtFile enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
if ([line length] > 0) {
[txtLines addObject:line];
}
}];
Update
#Evan is right, the above only works if blocks are available on your platform. A compiler directive around that code should take care of this limitation, e.g.:
#if NS_BLOCKS_AVAILABLE
// iOS 4.0+ solution
#else
// iOS 2.0+ solution
#endif
NSString *myListString = /* load / download file */
NSMutableArray *myList = [myListString componentsSeparatedByString:#"\n"];
You may have to use <br/> if it's HTML.
#octy's solution is only available in iOS 4.0 or later. This solution is iOS 2.0 or later. You can check the iOS version and choose which one to use:
BOOL useEnumeratedLineParsing = FALSE;
NSString *reqSysVer = #"4.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
useEnumeratedLineParsing = TRUE;
Then check the value of useEnumeratedLineParsing.
NSString *textFilePath = [[NSBundle mainBundle] pathForResource:#"urls" ofType:#"txt"];
NSString *fileContentsUrls = [NSString stringWithContentsOfFile:textFilePath encoding:NSUTF8StringEncoding error:nil];
NSArray *myArray = [urls componentsSeparatedByString:#"\n"];
As long as it isn't mega-large, you could read the whole file into an NSString.
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8Encoding error:nil];
Then split the lines:
NSArray *lines = [text componentsSeparatedByString:#"\n"];
And make it mutable:
NSMutableArray *mutableLines = [lines mutableCopy];
Now, depending on where your text file is coming from, you probably need to be more careful. It could be separated by \r\n instead of just \n, in which case your lines will contain a bunch of extra \r characters. You could clean this up after the fact, using something to remove extra whitespace (your file also might have blank lines which the above will turn into empty strings).
On the other hand, if you're in control of the file, you won't have to worry about that. (But in that case, why not read a plist instead parsing a plain text file...)