Using Lexicontext in your code
First, you need to import Lexicontext.h
so you can use the API
#import "Lexicontext.h"
Then you can obtain a reference to the dictionary:
Lexicontext *dictionary = [Lexicontext sharedDictionary];
The simplest use-case is the retrieval of a plain-text word definition. For example:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSString *definition = [dictionary definitionFor:@"Depone"];
That's it!
The basic use case is as simple as that.
To learn about more sophisticated usage scenarios read on...
- Using in Swift Apps
- HTML Definition
- NSDictionary Definition
- HTML with Custom Formatting
- HTML with Custom CSS
- Word Exists?
- Thesaurus
- Power Search
- Audio Pronunciation
- Random Word
- Dictionary Download
- HTML with Hyperlinked-Words
- Add new word definitions
- Images of words
Using in Swift Apps
To access the dictionary from a Swift app follow the steps below:
- Add
Lexicontext.h
,libLexicontext.a
&LexicontextAssets.bundle
to your project - Create an Objective-C bridging header for Lexicontext (create a header file named
Lexicontext-Bridging-Header.h
) - Add the line
#import "Lexicontext.h"
to the bridging header - Finally, to access the dictionary from your Swift app, do:
let dictionary = Lexicontext.sharedDictionary() let definition = dictionary.definitionFor("apple")
You can also download a sample Swift XCode project of a trivial Lexicontext-based Swift app.
More details about mixing Swift and Objective-C code can be found here
HTML Definition
You can get a word definition in HTML and display it inside a UIWebView
.
In the following example we use the default formatting:
UIWebView *webView = [[UIWebView alloc] init]; [self.view addSubview:webView]; ... Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSString *htmlDefinition = [dictionary definitionAsHTMLFor:@"Mumpsimus"]; [webView loadHTMLString:htmlDefinition baseURL:nil];
NSDictionary Definition
You can get the word definition as a structured NSDictionary
.
The NSDictionary
keys are the parts-of-speech (noun, verb, etc) and the corresponding value for each
key is an NSArray
of NSString
-s, where each string holds one possible
definition for that part-of-speech:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSDictionary *result = [dictionary definitionAsDictionaryFor:@"clear"]; NSLog(@"%@", result);
The (truncated) output from printing the resulting NSDictionary
is:
{ Adjective => ("readily apparent to the mind...", ... , "characteri..."); Adverb => ("completely...", "in an easily perceptible manner..."); Noun => ("the state of being free of suspicion...", "a clear or un..."); Verb => ("rid of obstructions...", ... , "free (the throat) by..."); }
HTML with Custom Formatting
The next example shows how to display a word definition with transparent background and customized formatting:
webView.backgroundColor = [UIColor clearColor]; webView.opaque = NO; ... Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSString *htmlDefinition = [dictionary definitionAsHTMLFor:@"Agerasia" withTextColor:@"FFFFFF" backgroundColor:@"transparent" definitionBodyFontFamily:@"Arial" definitionBodyFontSize:25]; [webView loadHTMLString:htmlDefinition baseURL:nil];
HTML with Custom CSS
We can also customize the definition's HTML using CSS. In the example below the definition will be displayed with green 40-pixel Courier fonts over a red background. Note that in this example there's really no need to provide a definition for anchors (the 'a' selector) because we did not enable word-hyperlinks (more information on word-hyperlinks is provided in the next section).
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSString *css = @""; NSString *htmlDefinition = [dictionary definitionAsHTMLFor:@"abecedarian" withStyleSheet:css]; [webView loadHTMLString:htmlDefinition baseURL:nil];
Word Exists?
The following example shows how to check if the dictionary contains a definition for a given word:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; BOOL wordExists = [dictionary containsDefinitionFor:@"Depone"];
Thesaurus
The following example shows how to lookup the synonyms of a word:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSDictionary *synomnyms = [dictionary thesaurusFor:@"Test"];
The result is an NSDictionary where the keys are the parts-of-speech for the input word (noun, verb, etc).The corresponding value for each key is an NSArray of NSArrays of NSStrings. Each array of strings contains a set of synonyms for that part of speech. The sets of synonyms for each part of speech are ordered by estimated frequency of use.
The (truncated) output from printing the result of the previous code snippet is:
{ Noun = ( (trial, trial run, test, tryout), (test, mental test, mental testing, psychometric test), (examination, exam, test), (test, trial), (test, trial, run) ); Verb = ( (test, prove, try, try out, examine, essay), (screen, test), (quiz, test) ); }
Power Search
The following example shows how to search for all the words that begin with "test":
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSDictionary *words = [dictionary wordsWithPrefix:@"Test"];
The result is an NSDictionary where the keys are the parts-of-speech for the input word (noun, verb, etc).The corresponding value for each key is an NSArray of NSStrings with all the results for that part of speech.
The (truncated) output from printing the result of the previous code snippet is:
{ Adjective = (test (adj), testaceous, testamentary, ...); Adverb = (test (adv), testily); Noun = (test (noun), test-cross, test-tube baby, test ban, ...); Verb = (test (verb), test drive, test fly, testify); }
You can also search for all the entries in the dictionary that contain a given search string (i.e. running "grep" on the dictionary):
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSDictionary *grepResult = [dictionary grep:@"Test"];
The result is an NSDictionary with a structure similar to the result of a prefix search. The (truncated) output from printing the result of the previous code snippet is:
{ Adjective = (test (adj), greatest, latest, ...); Adverb = (test (adv), fastest, testily); Noun = (test (noun), acid test, agglutination test, ...); Verb = (test (verb), attest, contest, ...); }
Audio Pronunciation of English Words with Lexicontext Pronounce
The Lexicontext Pronounce add-on adds to Lexicontext the functionality of audio pronunciation for a given dictionary word.
You get get the free Lexicontext Pronounce from our add-ons page. Note that it comes with the source code so you can further customize it to your needs. Please review the add-on's license before using it in your app.
Using Lexicontext Pronounce is very simple. The basic usage is shown below:
#import "Lexicontext+Pronounce.h" Lexicontext *dictionary = [Lexicontext sharedDictionary]; [dictionary pronounce:@"earnest"];
Random Word
It's sometimes useful to pick up a word at random. That's easily done:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSString *word = [dictionary randomWord];
Dictionary Download from Inside Your App with Lexicontext Fetch
If you don't want to bundle Lexicontext's data together with your app as a resource bundle (for example, you may want to reduce the app's original archive size or maybe you want to charge for it) you can fetch it after the app's installation, as a separate download.
In this scenario the zipped bundle is downloaded, extracted and saved
locally (in the app's Documents
folder, for example) and then Lexicontext
is constructed with the sharedDictionaryWithBundlePath
factory method.
The free Lexicontext Fetch add-on does most of the work for you and you can get it from our add-ons page. Note that it comes with the source code so you can further customize it to your needs.
To start the download add the following code somewhere in your "Downloader
" class
LexicontextFetch *fetcher = [[[LexicontextFetch alloc] init] autorelease]; NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; [fetcher fetchZippedBundleWithUrl:@"http://mysite.com/bundle.zip" targetFolder:docsDir fetchDelagate:self];
In the code above the data bundle is installed into the app's docs directory. Note also that Lexicontext Fetch assumes that you've zipped the LexicontextAssets.bundle directory and the URL points to the zipped bundle.
Last, note that in the code above we passed self
as the fetchDelagate
parameter. The LexicontextFetchDelegate
gets notified about the download & unzip progress
and one of your classes should adopt this protocol. Assuming the name of this class is
Downloader
, its header would be similar to:
#import "LexicontextFetch.h" ... @interface Downloader : NSObject <LexicontextFetchDelegate> { ...
You implement the methods you need from LexicontextFetchDelegate
.
For example, if you want to show a progress bar during the download, implement the
lexicontextDidReceiveBytes
method:
- (void)lexicontextDidReceiveBytes:(NSInteger)bytesReceived totalBytes:(NSInteger)totalBytes { NSLog(@"Downloaded %d out of %d bytes", bytesReceived, totalBytes); }
You should at least implement lexicontextUnzipDidSucceed
which notifies you
that the download and unzip process has finished successfully and then you can construct the dictionary:
- (void)lexicontextUnzipDidSucceed:(NSString *)targetFolderPath { NSString *bundlePath = [targetFolderPath stringByAppendingPathComponent: @"LexicontextAssets.bundle"]; Lexicontext *dictionary = [Lexicontext sharedDictionaryWithBundlePath: bundlePath]; }
In the code above @"LexicontextAssets.bundle"
is the name of the bundle after
the Zip file is extracted. In subsequent initializations of the dictionary you won't download the
dictionary again... You will construct it via [Lexicontext sharedDictionaryWithBundlePath:bundlePath]
where bundlePath
is the path where the bundle was saved by the fetch process.
HTML with Hyperlinked-Words
The last example shows how to present the definition so that if the user touches a word, the application is notified of this. In a typical scenario, the application will then present the word definition of the word that the user has touched (i.e. a drill-into feature)
The only addition to the Lexicontext code is that we have to specify the name of the custom scheme for the word-hyperlinks (line #2). This is done as follows:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; dictionary.touchableWordsURLScheme = @"mylexiconschema"; // custom scheme name NSString *htmlDefinition = [dictionary definitionAsHTMLFor:@"Mumpsimus"]; [webView loadHTMLString:htmlDefinition baseURL:nil];
We also need to add a handleOpenURL
method to our UIApplicationDelegate
subclass, so that iOS will invoke the method when the user touches a word:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{ NSString *touchedWord = [Lexicontext touchedWord:url]; NSLog(@"Touched Word: %@", touchedWord); return YES; }
Finally, we need to register the custom URL scheme for our application as described in the section "Implementing Custom URL Schemes" in this iOS developer library article. Another article (with screenshots) can be found here.
Note that in this example we assume that the custom URL scheme name is
mylexiconschema
The following image shows our application's info.plist
file after adding the
custom URL scheme:
Add New Word Definitions
The next example shows how to add a new word definition to Lexicontext:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; [dictionary addDefinitionFor:@"against" withDefinition:@"In opposition to" andPartOfSpeech:@"Preposition"];
You can add multiple definitions for the same word (for example, when the word belongs to multiple parts-of-speech) by calling this methods multiple times with a different definition each time.
Images of Words
Via the the ImageNet service Lexicontext provides access to the images of a word.
The next example shows how you can get an array containing links to images for a given word:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSArray *imageURLs = [dictionary imageURLsFor:@"apple"];Important Note:
ImageNet is based on WordNet 3.0, whereas the latest version of Lexicontext is based on WordNet 3.1.
Therefore, until ImageNet upgrade to WordNet 3.1, if you want to use the image URLs feature, you will
have to downgrade the WordNet data files inside your Lexicontext's data bundle (typically named
LexicontextAssets.bundle).
Download a zip with
the WordNet 3.0 data files, unzip it and then replace the folder
LexicontextAssets.bundle/Contents/Resources/WordNet/dict
with the one you can find inside the extracted zip.
ImageNet is an image dataset organized according to the WordNet hierarchy. ImageNet define the concept of a "WordNet ID". Once you have this ID use can use ImageNet's various image-related APIs.
The next example shows how to get the WordNet ID for a given word:
Lexicontext *dictionary = [Lexicontext sharedDictionary]; NSString *imagenetId = [dictionary imageNetIdFor:@"dog"];