Académique Documents
Professionnel Documents
Culture Documents
v. 1.9.7
NimbleKit SDK
Documentation
Version 1.9.7 Created on 25.03.09 Last modied on 28.06.11 Authors: Alexander Voloshyn! Eugen Belyakov !! Editors: Anna Novikova! ! ! novikova@nimblekit.com ! ! voloshyn@nimblekit.com belyakov@nimblekit.com
NimbleKit SDK!
v. 1.9.7
Contents:
NimbleKit SDK Documentation!
Overview! Requirements! Compatibility and Dependencies! Documentation! Quick Start! Registering NimbleKit!
13
13 13 13 13 13 13
14
14 14 14 14 14 14 14 15 15 15 15
16
16 16 16 16 16 16 16 16 17 17 17 17 2
v. 1.9.7
Examples:!
17
18
18 18 18 18 18 18 18 18 18 18 18 18 19 19
Examples:!
19
20
20 20 20 20 20 20 20
NKSlider!
Overview! init(x, y, width, callback)! show()! hide()! setValue(value)! Copyright VolnaTech 2009-2010!
21
21 21 21 21 21 3
NimbleKit SDK!
v. 1.9.7
NKBanner!
Overview! init(x, y, isHorizontal)! show()! hide()!
22
22 22 22 22
Callbacks:!
bannerViewDidLoadAd()! didFailToReceiveAdWithError(error)! bannerActionShouldBeginWillLeaveApplication(isLeaving)! bannerViewActionDidFinish()!
22
22 22 22 22
22
NKButton!
Overview! init(x, y, width, height, callback)! show()! hide()! setImage(imageName)! setTitleColor(r, g, b)! setTitle(title)!
24
24 24 24 24 24 24 24
NKToolBar!
Overview! init(y)! show()! hide()! addButton(title, imageName, callback)! insertButtonAtIndex(index, title, image, callback)! addDoneButton(title, callback)! addFlexibleSpace()! setStyle(style)! setTintColor(red, green, blue)! destroy()! removeButtonAtIndex(index)!
25
25 25 25 25 25 25 25 25 25 25 25 26
NKTextView!
Copyright VolnaTech 2009-2010!
27
4
NimbleKit SDK! Overview! init(x, y, width, height)! show()! hide()! setString(value)! getString()! setFontSize(size)! setEditable(value)! 27 27 27 27 27 27 27 27
v. 1.9.7
NKTextField!
Overview! init(x, y, width, height)! show()! hide()! setString(value)! getString()! setKeyboardType(keyboardType)! setTextChangeCallback(callback)! setBorderStyle(style)! setPlaceholder(placeHolder)! dismissKeyboard()! showKeyboard()! setSecure(isSecure)!
28
28 28 28 28 28 28 28 28 28 28 28 29 29
NKLabel!
Overview! init(x, y, width, height, value)! show()! hide()! setString(newValue)! setTextFontSize(size)! setTextColor(r, g, b)!
30
30 30 30 30 30 30 30
NKTableView!
Overview! init(x, y, width, heigh, style)! show()! Copyright VolnaTech 2009-2010!
31
31 31 31 5
NimbleKit SDK! hide()! setEditing(isEditing)! setUserCanEditRows(canEdit)! insertCategoryNamed(name)! insertRecord(title, subtitle, image, sectionNumber, rightImage, callback)! bindToDataBase(dbName, tableName, optionalQuery)! commitDatabaseChanges()! setShowsIndex(indexAllowed)! setRowHeight(height)! insertRecords(records)! setOnRowRemovedCallback(callback)! 31 31 31 31 31 31 32 32 32 32 32
v. 1.9.7
NKModalWindow!
Overview! show()! dismiss()! addControl(control)!
34
34 34 34 34
NKImageView!
Overview! init(x, y, width, height, imageName)! show()! hide()! setImage(imageName)! setOnClickCallback(callback)!
35
35 35 35 35 35 35
NKSwitch!
Overview! init(x, y,callback)! show()! hide()! getState()! setState(value)!
36
36 36 36 36 36 36
NKProgressBar!
Overview! init(x, y, width)! show()! Copyright VolnaTech 2009-2010!
37
37 37 37 6
v. 1.9.7
NKActivityIndicator!
Overview! init(x, y, size, style)! show()! hide()! stop()! spin()!
38
38 38 38 38 38 38
NKContact!
Overview! contacts()! searchContact(argument)! showPeoplePicker(callback)!
39
39 39 39 39
NKAudioPlayer!
Overview! loadFile(leName)! loadFileFromDocuments(leName)! play()! stop()! pause()! resume()! getDurationInSeconds()! setPositionInSeconds(seconds)! getCurrentPositionInSeconds()! setPlayingFinishedCallback(callback)! setLoopMode(isInLoop)! setVolume(volume)! dispose()! setIgnoreLock(isIgnored)!
40
40 40 40 40 40 40 40 40 40 40 40 40 40 40 41
NKVideoPlayer!
Overview! openURL(url)! openFileName(leName)! Copyright VolnaTech 2009-2010!
42
42 42 42 7
v. 1.9.7
NKSystemVolumeControl!
Overview! init(x, y, width)!
43
43 43
NKAlertSheet!
Overview! init(callback)! addButtonWithTitle(title)! setStyle(style)! setTitle(title)! setRedButtonIndex(index)! setBlackButtonIndex(index)!
44
44 44 44 44 44 44 44
NKFile!
Overview! open(leName)! openFromDocuments(lename)! read(position, length)! position()! close()! size()! deleteFile()!
46
46 46 46 46 46 46 46 46
NKSettings!
Overview! getValueForKey(key)! setValueForKey(value, key)!
47
47 47 47
NKFileDownloader!
Overview! openURL(url)! start(leName)! stop()! getProgress()!
48
48 48 48 48 48
NKSQLite!
Copyright VolnaTech 2009-2010!
49
8
v. 1.9.7
NKMapView!
Overview! init(x,y,width,height)! show()! hide()! showUserlocation()! setMapType()! getUserLocation(callback)! isUserLocationUpdating()! setDisplayRegion(lat, longtitude, latDelta, longtitudeDelta)! addAnnotation(lat, longitude, title, subtitle, image, color, callback)! selectAnnotation(title)! setDelegateCallback(callback)! clearAnnotations()! getDisplayRegion()! setCenterCoordinate(latitude, longitude, isAnimated)!
50
50 50 50 50 50 50 50 50 50 50 51 51 51 51 51
Callbacks:!
mapTouchedAtCoordinates(latitude, longitude)!
51
51
NKAppStore!
Overview! getAvailableProducts(callback, productIDs)! requestInfoForProductAtIndex(index, callback)! buyProductWithID(identicator, callback)!
53
53 53 53 53
NKPasteboard!
Overview! getString()! setString(value)! getURL()! setURL(value)! Copyright VolnaTech 2009-2010!
54
54 54 54 54 54 9
NimbleKit SDK!
v. 1.9.7
NKImage!
Overview! loadURL(url)! loadFromDocuments(leName)! loadFromBundle(leName)! loadFromBase64(base64String)! getBase64(compression)! setSize(width, height)! saveToLibrary()! saveToDocuments(name)! getSize()! rotate(degrees)!
55
55 55 55 55 55 55 55 55 55 55 55
NKMailComposer!
Overview! show()! setSubject(subject)! setRecipient(recipients)! setCC(value)! setBCC(value)! setBody(body)! addImage(image)!
56
56 56 56 56 56 56 56 56
NKSMSComposer!
Overview! setRecipient(value)! setBody(text)! show()!
57
57 57 57 57
NKPopoverController!
Overview! init(contentPage)! show(x, y, width, height)! hide()! setContentSize(width, height)!
58
58 58 58 58 58
NKWebView!
Overview! Copyright VolnaTech 2009-2010!
59
59 10
NimbleKit SDK! init(x, y, width, height)! show()! hide()! loadURL(url)! setScalesToFit(isScaled)! loadHTML(html, baseURL)! loadFromBundle(name)! goBack()! goForward()! reload()! setOnFinishCallback(callback)! setDetectsPhoneNumbers(detectionAllowed)! 59 59 59 59 59 59 59 59 59 59 59 59
v. 1.9.7
NimbleKit functions!
NKGetUniqueIdentier()! NKGetDeviceType()! NKSetPageOpaque(page, isOpaque)! NKSetBackground(leName)! NKIsInternetAvailableViaCellularNetwork! NKIsInternetAvailableViaWi ! NKAlert(title, message)! NKMoveToPageAnimated(pageName, animation)! NKOpenURLInSafari(url)! NKOpenDocument(name, source)! NKStartPreloadingPage(pageName)! NKReloadPage(pageName)! NKGetLibraryVersion()! NKSetWebViewBackgroundColor(red, green, blue, alpha)! NKGetParameter(name)! NKLog(message)! NKConrm(title, message, bTitle1, bTitle2, callback)! NKExecuteJavascriptOnPage(jscode, pagename)! NKGetAppVersion()! NKPreloadPage(pageName, callback)!
61
61 61 61 61 61 61 61 61 62 62 62 62 62 62 62 62 62 63 63 63
64
64 11
NimbleKit SDK! NKNativeControlRotate(control, degrees)! NKSetControlAutoresizingMask(control, mask)! NKNativeControlSetAlpha(control, alpha)! NKNativeControlEnable(control, isEnabled)! NKControlSetBackgroundColor(control, r, g, b, a)! 64 64 64 64 65
v. 1.9.7
66
66 66
67
67 67 67
Orientation support!
NKIsPageSupportsAutoOrientation()! pageWillRotate(degree)! pageDidRotate()!
68
68 68 68
Application Events!
OnApplicationQuit()! OnApplicationPause()! OnApplicationResume()! onPageShown(caller)! onPageHidden()!
69
69 69 69 69 69
FAQ!
1. How to add fullscreen company logo on application start?! 2. How to set image behind page so it is visible when user scrolls page?!
70
70 70
Troubleshooting!
Overview! Threading!
71
71 71
12
NimbleKit SDK!
v. 1.9.7
Requirements
Mac OS X 10.6.2 or newer iPhone SDK 4.2 or newer
Documentation
Documentation updates with every release of NimbleKit, for an updated documentation please visit http://nimblekit.com and download latest version.
Quick Start
After you installed Nimble SDK there will be added new Xcode template which has to be used to create Nimble Kit based applications.
Registering NimbleKit
After NimbleKit SDK is purchased, projects can be activated to run on iOS devices. To do that open project and navigate to le named YOUR_APPLICATION_NAMEDelegate.m and enter serial in serial eld for example:
Nimble *nimble = [[Nimble alloc] initWithRootPage:@"main.html" window:window serial:@"YOUR-SERIAL-HERE"];
13
NimbleKit SDK!
v. 1.9.7
NKTabBarController()
Creates and initializes NKTabBarController object also makes empty tab controller to appear on screen.
destroy()
Completely removes controller from page
page - name of page to be displayed when tab selected title - title to be displayed on tab icon image - image to be displayed over tab title, if you want to use standard iPhone images, you can specify image number from the list instead of lename:
UITabBarSystemItemFavorites = 1 UITabBarSystemItemFeatured = 2 UITabBarSystemItemTopRated = 3 UITabBarSystemItemRecents = 4 UITabBarSystemItemContacts = 5 UITabBarSystemItemHistory = 6 UITabBarSystemItemBookmarks = 7 UITabBarSystemItemSearch = 8 UITabBarSystemItemDownloads = 9 UITabBarSystemItemMostRecent = 10 UITabBarSystemItemMostViewed = 11 Example:
setBadgeCountAtIndex(badgeCount, index)
sets badges count for tab at given index (small red circles shown on top of tabs)
selectTabAtIndex(index)
selects tab at given index
getTabPotionsArray()
returns javascript array of tab pageNames sorted in order as user reordered them having "more" tab, used to save the positions of rearranged tabs and be able to restore same order on next application launch.
14
NimbleKit SDK!
v. 1.9.7
setOnTapCallback(callback)
sets callback to be called when user taps on tab bar, callback format is following callback(pageName), where pageName is the name of the page been taped.
getSelectedTab()
returns a le name of currently selected tab, for instance main.html
Example:
var tabController = new NKTabBarController; var settings = new NKSettings; var array = settings.getValueForKey("tabOrder"); if (array.length>0 && array!="(null)") { ! for (i=0; i<array.length; i++) ! ! tabController.setTabBarForPage(array[i], array[i], ""); } else { ! tabController.setTabBarForPage("main.html", "main.html", ""); ! tabController.setTabBarForPage("1.html", "1.html", ""); ! tabController.setTabBarForPage("2.html", "2.html", ""); ! tabController.setTabBarForPage("3.html", "3.html", ""); ! tabController.setTabBarForPage("4.html", "4.html", ""); ! tabController.setTabBarForPage("5.html", "5.html", ""); ! tabController.setTabBarForPage("6.html", "6.html", ""); } function OnApplicationQuit() { ! array = tabController.getTabPositionsArray(); ! settings.setValueForKey(array, "tabOrder"); }
setTabForPageDisabled(page, disabled)
sets tab disabled or enabled page - page name of tab you want to set state for disabled - state you want to set. pass true or 1 to disable, false or 0 to enable
Example:
var tabController = new NKTabBarController; tabController.setTabForPageDisabled(main.html, true);
15
NimbleKit SDK!
v. 1.9.7
setTitle(title)
Set navigation controller title for current page.
setImage(imageName)
Set navigation controller image for current page.
setTintColor(r, g, b)
sets tint color for navigation bar.
Parameters: red, green and blue component of the color
hide()
Hides navigation bar.
show()
Shows navigation bar if it was hidden.
title - a string title to appear on button callback - a string function name to be called when user pressed navigation item image - name of the image to use or index of the image from standard icon list starting from 1:
UIBarButtonSystemItemDone, = 1 UIBarButtonSystemItemCancel, UIBarButtonSystemItemEdit, UIBarButtonSystemItemSave, UIBarButtonSystemItemAdd, UIBarButtonSystemItemFlexibleSpace, - does nothing UIBarButtonSystemItemFixedSpace, - does nothing UIBarButtonSystemItemCompose, UIBarButtonSystemItemReply, UIBarButtonSystemItemAction, UIBarButtonSystemItemOrganize, UIBarButtonSystemItemBookmarks, UIBarButtonSystemItemSearch, UIBarButtonSystemItemRefresh, UIBarButtonSystemItemStop, UIBarButtonSystemItemCamera, UIBarButtonSystemItemTrash, UIBarButtonSystemItemPlay, UIBarButtonSystemItemPause, UIBarButtonSystemItemRewind, UIBarButtonSystemItemFastForward, UIBarButtonSystemItemUndo,! ! // available in iOS 3.0 UIBarButtonSystemItemRedo,! ! // available in iOS 3.0
removeNavigationItem()
removes navigation item added by addNavigationItem() method
16
NimbleKit SDK!
v. 1.9.7
gotoPage(pageName)
navigates to given page creating back navigation button to allow to go to the previous page you also allowed to pass GET parameters to pageName, for example page.html? id=35&name=me, see NKGetParameter function for retrieving parameters.
Parameters:
setStyle(style)
sets the style of navigation controller
Parameters:
style is one of two values available: Default and Black (not case sensitive).
goBack()
returns to previous page
setUsesPreloading(isUsePreloading)
manages state of automatic page preloading isUsePreloading can take state yes, no, 1 and 0.
destroy()
completely removes controller from page
setTitleForPage(title, page)
sets navigation controllers title for specied page
popToRootView(isAnimated)
returns to the rst page in pages stack either animated or instantly, can take parameters yes/no or 1/0 Examples:
<html> <head> <meta name = "viewport" content = "width = 320, initial-scale = 1.0, user-scalable = no" /> </head> <body> <script type="text/javascript" src="NKit.js"></script> <script type="text/javascript"> var navController = new NKNavigationController(); navController.setTitle("Colored"); navController.setTintColor(0xFF, 0, 100); </script> <a href="#" onClick="navController.gotoPage('nextPage.html')">Go forward</a> </body> </html>
17
NimbleKit SDK!
v. 1.9.7
NKInternetPlayer()
creates and initializes InternetPlayer instance, which acts as singleton, so if you created InternetPlayer before current instance will just reuse resources.
playFromURL(url)
tries to play streamed media from given URL
stop()
stops current InternetPlayer, does nothing if no media
mute()
mutes current InternetPlayer, does nothing if no media
notifyPlayingStarted(callback)
noties when caching is nished and actual playback started, callback is a string name of the function to be called
notifyPlayingStopped(callback)
noties when playback stopped, callback is a string name of the function to be called
seekToPosition(seconds)
seeks to specied position in seconds, works when playing le from internet, does not work on real streams.
getDurationInSeconds()
returns duration of the streamed le in seconds (duration may change during playback and is approximated)
getCurrentPositionInSeconds()
returns current position in streamed le, this value is approximated
Parameters:
callback - javascript function to be called when playback started, should not contain any parameters.
setVolume(volume)
sets volume for current audio stream
Parameters:
getCurrentMetaString()
returns current streams metadata (StreamTitle and optionally StreamUrl). Works with Shoutcast and Icecast stream services
Copyright VolnaTech 2009-2010! 18
NimbleKit SDK!
v. 1.9.7
forceDecoderFormat(format)
species decoder format to use, this is often an issue for AAC or AAC+ streams when server does not provide information about decoder to be used, can take values aac and mp3.
setMaximumBuffersCount(count)
sets maximum buffers to use, consider using smaller amount for real streamed audio (2-16) and bigger amount for static les hosted in the web (16-128). Each buffer has size of 32 Kilobytes. Default value is 64 buffers, which is 2Mb cache and most suitable for most cases. Examples:
function playRadio() { var radio = new NKInternetPlayer();
} function { }
radio.notifyPlayingStarted("stopLoadingIndicator"); radio.forceDecoderFormat("aac");
radio.playFromURL("http://radio.myserver.com:8080"); stopRadio() var radio = new NKInternetPlayer(); radio.stop();
19
NimbleKit SDK!
v. 1.9.7
setStatusBarStyle(style)
sets the color and style of topmost status bar
Parameters:
style - can be one of three available values: Default, Black, BlackTranslucent (not case sensitive).
Example: var application = new NKApplication(); application.setStatusBarStyle("black");
setIdleTimerDisabled(isDisabled)
Controls applications idle timer. You should set idle timer disabled only if its really necessary and be sure to enable idle timer when the need no longer exists. By default idle timer enabled.
Parameters:
vibrate()
Makes iPhone device to vibrate
setBadgeCount(count)
sets number of application badges (shown on application icon in red circle)
iPhoneOSVersion()
retrieves string which represents iOS version (i.e. 3.0)
getCurrentLocale()
returns current locale (i.e. en_US, etc)
20
NimbleKit SDK!
v. 1.9.7
NKSlider
Overview
Creates native Cocoa Touch slider. Control is created on the top layer of page, so if there are html elements on given coordinates control will overlap them.
x - left coordinate of the control y - bottom coordinate of the control width - horizontal size of the control callback - javascript function to be called when slider changes value. This callback uses 2 parameters - absolute value of slider value and controlID which is an ID of the control, in case you have one callback for many controls.
show()
shows initialized slider, does nothing if its shown already
hide()
hides initialized slider, does nothing if its hidden already
setValue(value)
sets current value [0..100]
Example: function VolumeChanged(volume) { radio.setVolume(volume); } var slider = new NKSlider(); slider.init(20, 325, 280, "VolumeChanged"); slider.setValue(20); slider.show();
21
NimbleKit SDK!
v. 1.9.7
NKBanner
Overview
NKBanner class is used to add advertisement to iPhone apps running iOS 4.0 and newer (iAd).
init(x, y, isHorizontal)
initializes advertisement view with given coordinates, multiple calls to this method change only position without reinitializing the control (hidden by default). isHorizontal parameter can take values "yes"/"no" or 1/0 which is used to specify orientation for the banner requested.
show()
shows initialized banner view (banners are initially hidden)
hide()
hides advertisement view Callbacks:
All callbacks have to be implemented on the page where specic NKBanner was created, they will be called automatically. bannerViewDidLoadAd()
called when iAd banner is loaded and ready to be shown. Usually only in this method you need to show the ad. If you show the banner before then application can be rejected in the App Store.
didFailToReceiveAdWithError(error)
called when error happened during iAd retrieving. This method must be implemented and if case error happened and invoked error must be processed and appropriate actions taken otherwise the application may be rejected in the App Store.
bannerActionShouldBeginWillLeaveApplication(isLeaving)
this callback is called when iAd banner was clicked. isLeaving parameter can be either YES or NO means either ad needs to quit the application to proceed or ad can show the information without closing the application.
bannerViewActionDidFinish()
called when banner action view has been dismissed and the application is active again.
Please see callbacks usage in the sample code below Sample usage:
var banner = new NKBanner; banner.init(0, 0); function bannerViewDidLoadAd() { ! NKLog("We have the banner loaded, now we can show it"); ! NKLog("Btw, after creating we still can reposition it by calling init function"); ! banner.init(0, 410); // show the banner at the bottom ! banner.show();
22
NimbleKit SDK!
} function didFailToReceiveAdWithError(error) { ! NKLog(error); } function bannerActionShouldBeginWillLeaveApplication(isLeaving) { ! if (isLeaving == "YES") ! { ! ! NKLog("iad quits this app to proceed"); ! } ! else ! { ! ! NKLog("iad clicked, but the app is still remains launched"); ! } } function bannerViewActionDidFinish() { ! NKLog("Banner action is finished and now we returned back to the our application"); }
v. 1.9.7
Available only on devices running iOS 4.0 or newer, added in NimbleKit version 1.9.2 iAd callbacks added in v 1.9.3
23
NimbleKit SDK!
v. 1.9.7
NKButton
Overview
Creates native Cocoa Touch button. Control is created on the top layer of page, so if there are html elements on given coordinates control will overlap them.
x - left coordinate of the control y - top coordinate of the control width - horizontal size of the control height - vertical size of the control callback - javascript function to be called when slider changes value. This callback has one parameter - controlID, which is an ID of the control, in case you have one callback for many controls
show()
shows initialized button, does nothing if its shown already
hide()
hides initialized slider, does nothing if its hidden already
setImage(imageName)
sets the image to be displayed over the button, images are not scaled and appear in real size.
setTitleColor(r, g, b)
sets the color of the button title, specied in r, g, b, as color components of red, green and blue. Parameters can take values in range [0..255].
setTitle(title)
sets the title to be displayed over the button
Example:
function playRadio() { var radio = new NKInternetPlayer(); radio.playFromURL("http://myradio.com:8000"); } var playButton = new NKButton(); playButton.init(15, 390, 60, 20, "playRadio"); playButton.setImage("play.png"); playButton.show();
24
NimbleKit SDK!
v. 1.9.7
NKToolBar
Overview
Class is used as an utility toolbar
init(y)
Initializes toolbar with vertical position y
show()
shows initialized toolbar
hide()
hides initialized toolbar
title - button title to be displayed (ignored if imageName specied) imageName - the lename of bundled image to be displayed on button (discards title) callback - javascript function name to be called when button pressed
index - index, used to specify button position, count starts from 1 title - button title to be displayed (ignored if imageName specied) imageName - the lename of bundled image to be displayed on button (discards title) callback - javascript function name to be called when button pressed
addDoneButton(title, callback)
creates blue button on toolbar, which has same style is used for Done buttons
addFlexibleSpace()
adds exible space into toolbar, used to align buttons
setStyle(style)
sets the style of toolbar, possible values are: black, blacktranslucent, default
destroy()
removes and destroys toolbar and resources allocated for it.
25
NimbleKit SDK!
v. 1.9.7
removeButtonAtIndex(index)
removed button at specied index (starts at 0)
26
NimbleKit SDK!
v. 1.9.7
NKTextView
Overview
This control is used to display large amount of text.
show()
shows control (not creating)
hide()
hides control (not destroying)
setString(value)
sets string value in control
getString()
synchronous method returning contents of the control in string form (if you need other type please use parseInt, parseFloat, etc)
setFontSize(size)
sets the font size for initialized view
setEditable(value)
enables/disables ability to edit for user. Variable value can take following values: yes, no, 1, 0.
Example:
var textView = new NKTextView; textView.init(0, 0, 320, 100); textView.setEditable("no"); textView.setString("HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD"); textView.setFontSize(20); textView.show();
27
NimbleKit SDK!
v. 1.9.7
NKTextField
Overview
This control is used for user text input
show()
shows control (not creating)
hide()
hides control (not destroying)
setString(value)
sets string value in control
getString()
synchronous method returning contents of the control in string form (if need you other type please use parseInt, parseFloat, etc)
setKeyboardType(keyboardType)
sets the type of keyboard
Parameters:
keyboardType: the type of keyboard to use, available values are: ASCII, NumbersAndPunctuation, URL, NumberPad, PhonePad and EmailAddress, from iOS 4.1 DecimalPad also available, if the device has older OS NumberPad will be used automatically instead.
setTextChangeCallback(callback)
sets the callback which will be called every time text eld is modied, format is following callback(newValue), where newValue is the new modied value of the text eld
setBorderStyle(style)
sets border style for the text view, possible values are: "none", "line", "bezel", "rounded", the default value is "rounded".
setPlaceholder(placeHolder)
sets placeholder string which will be shown before user input starts Available in NimbleKit 1.7 or newer
dismissKeyboard()
dismisses text eld keyboard
28
NimbleKit SDK!
v. 1.9.7
showKeyboard()
makes text eld rst responder. Should be used ONLY after all controls are created, for example if you call show keyboard and then create new button then it wont work. Available in NimbleKit 1.7 or newer
setSecure(isSecure)
sets the secure type of keyboard, all input will be replaced by bullets. Takes parameters yes or no. Available in NimbleKit 1.7 or newer
Example:
var textFied = new NKTextField(); textFied.init(20, 120, 200, 30); textFied.setKeyboardType("PhonePad"); textFied.show();
29
NimbleKit SDK!
v. 1.9.7
NKLabel
Overview
NKLabel class is used to display static text
show()
shows initialized label on current view
hide()
hides initialized label from current view
setString(newValue)
sets new value to the labels text
setTextFontSize(size)
sets the font size for initialized label
setTextColor(r, g, b)
sets the color of the text using red, green and blue components [0..255]
30
NimbleKit SDK!
v. 1.9.7
NKTableView
Overview
TableView objects are used to present hierarchical lists of information.
show()
shows initialized table view on the screen
hide()
hides initialized table view (allowing click-though)
setEditing(isEditing)
switches tableview to editing mode, where user can manipulate table rows, reorder and remove any rows. Parameter isEditing can be either yes or no.
setUserCanEditRows(canEdit)
enables/disables ability to delete rows using swipe gestures, be default this is disabled.
insertCategoryNamed(name)
inserts new category/section in table view with specied name.
title - rows main title subtitle - rows subtitle, usually it is a description for the title image - NKImage instance, which represents the image to be displayed in the left part of the row. Images larger then row height will be down scaled to row height. Images smaller then row height will appear at their original size. sectionNumber - number of the section where the row must be inserted (starting from 0). rightImage - small image to be displayed in the right part of the row, usually showing that the item is clickable, if empty then default OSs action image will be used. callback - is a real javascript code to be executed when the item is clicked.
NimbleKit SDK!
v. 1.9.7
are named exactly like following: category - name of the category to which the row is related (for example Fruits) title - Rows main title (for example Apple) subtitle - Rows subtitle/description (for example Nice green fruit) image - the name of the image le which will be used in the left part of the row, can be the name from application bundle, documents folder or even an url to the image in the internet. right_image - the image name if the small image to be displayed in the right part of the row, usually showing that the item is clickable, if empty then default OSs action image will be used. Can be the name from application bundle, documents folder or even an url to the image in the internet. js - javascript code to be executed when the row is clicked. This is very useful as it will be loaded much faster then the code on the page, making application more responsive and page to load faster improving user experience. If you want to apply lter or resort data in table view you can call bindToDatabase multiple times with different "optionalQuery"s.
commitDatabaseChanges()
ushes changes made to the table view (using setEditing) into the database. This method isnt must have, on application quit changes will be ushed anyway, however different situations may occur. This function works only if database has been bound to the table view. Warning: if you quit iPhone simulator using CMD+Q then changes arent written into the database, make sure your either using commitDtaabaseChanges or quit simulator app using home button, this warning is only applies for iPhone/iPad simulator.
setShowsIndex(indexAllowed)
allows showing/hiding index in table view. indexAllowed can take values yes and no
setRowHeight(height)
sets the row height for all rows in table. height - rows height in pixels
insertRecords(records)
inserts array of records to the table records - array of records
setOnRowRemovedCallback(callback)
adds callback to be called when user manually removed a row in the table view (setUserCanEditRows is enabled). The callback itself is a string name of the function which takes 2 parameters: section number and row number.
Example:
! ! ! ! ! ! !
var tableView = new NKTableView(); tableView.init(20, 20, 280, 300, 'plain'); tableView.show(); tableView.insertCategoryNamed('FirstGroup'); tableView.insertCategoryNamed('SecondGroup'); tableView.setOnRowRemovedCallback(itemRemoved); var image = new NKImage();
32
NimbleKit SDK!
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! image.loadFromBundle('arrow.png'); var firstRecord = new Object; firstRecord.title = "Record1"; firstRecord.subTitle = "subtitle" firstRecord.imageID = image.id;//note image ID is used firstRecord.rightImageID = image.id;//note image ID is used firstRecord.section = 0; firstRecord.callback = "onRowClick()"; var secondRecord = new Object; secondRecord.title = "Record2"; secondRecord.section = 1; var records = new Array();! records[0] = firstRecord; records[1] = secondRecord; tableView.insertRecords(records); function itemRemoved(section, rowInSection) { NKAlert("Row removed", "at section:"+section+" row:"+rowInSection); }
v. 1.9.7
33
NimbleKit SDK!
v. 1.9.7
NKModalWindow
Overview
This class is used to present modal dialogs and wait screens when user should not access any other controls except those placed on modal window
show()
shows modal window on top of all controls
dismiss()
removes modal window from the screen
addControl(control)
adds control to the modal window, can take value of standard NimbleKit controls, like NKActivityIndicator, NKButton, NKLabel, etc
Example:
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! modal = new NKModalWindow(); modal.show(); var indicator = new NKActivityIndicator(); indicator.init(90, 165, 30, "white"); indicator.show(); indicator.spin(); modal.addControl(indicator); var label = new NKLabel(); label.init(140, 158, 140, 40, "Please wait..."); modal.addControl(label); label.show(); var button = new NKButton(); button.init(120, 210, 100, 40, "buttonClick"); button.setTitle("Dismiss"); modal.addControl(button); button.show();
34
NimbleKit SDK!
v. 1.9.7
NKImageView
Overview
Image view class is used to display images on top of a web view.
show()
shows on screen initialized NKImageView class instance
hide()
hides on screen initialized NKImageView class instance
setImage(imageName)
sets new image to be displayed, can be either name of the bundled image or URL to the image in the internet. From v 1.7 this API is deprecated, use setImageObject instead
setOnClickCallback(callback)
Sets the callback to be called when user taps on image view. Callback is a string name of javascript function to be called (i.e. myOnclickHandler())
35
NimbleKit SDK!
v. 1.9.7
NKSwitch
Overview
This control is used as switch which has boolean value
init(x, y,callback)
initializes switch control with given coordinates and callback (name of the function as string) to be called when switch value has been changed, callback format should be functionName(newValue, controlID), "newValue" can be either 1 or 0 and controlID is an ID of the control, in case you have one callback for many controls.
show()
shows switch
hide()
hides switch control
getState()
asynchronous method which returns state of the switch (0 or 1)
setState(value)
sets the state of the switch with animation
Example:
<script type="text/javascript"> var uiswitch = new NKSwitch(); uiswitch.init(20, 70); uiswitch.show(); </script> <a href="#" onClick="uiswitch.setState(!uiswitch.getState());">Switch State</a>
36
NimbleKit SDK!
v. 1.9.7
NKProgressBar
Overview
Creates native Cocoa Touch progress view. Control is created on the top layer of page, so if there are html elements on given coordinates control will overlap them.
init(x, y, width)
Initializes progress bar
Parameters:
x - left coordinate of the control y - bottom coordinate of the control width - horizontal size of the control
show()
shows initialized progress bar, does nothing if its shown already
hide()
hides initialized progress bar, does nothing if its hidden already
setPosition(value)
sets position of the slider.
Example:
var progress = new NKProgressBar(); progress.init(70,70,100); progress.setPosition(35); progress.show();
37
NimbleKit SDK!
v. 1.9.7
NKActivityIndicator
Overview
Creates native Cocoa Touch activity indicator. Control is created on the top layer of page, so if there are html elements on given coordinates control will overlap them.
x - horizontal coordinate of the control y- vertical coordinate of the control size - vertical and horizontal size of the control style - species the color of the control, can be one out of two values: grey, white.
show()
shows initialized and stopped activity indicator
hide()
hides initialized activity indicator, no matter which state it has
stop()
stops controls animation, does nothing if its not animating
spin()
starts controls animation, does nothing if control already animating
Example:
In this example activity indicator created and started when play button pressed and stopped when radio finished caching and started to play var indicator = new NKActivityIndicator(); indicator.init(10,10,20,"white"); function radioStartedToPlay() { indicator.stop(); } function playRadio() { var radio = new NKInternetPlayer(); radio.notifyPlayingStarted("radioStartedToPlay"); indicator.show(); indicator.spin(); radio.playFromURL("http://myradio.com:8000"); }
38
NimbleKit SDK!
v. 1.9.7
NKContact
Overview
Used to retrieve information from address book
contacts()
retrieves all contacts from address book and returns them as a string in format name, phone<br>
searchContact(argument)
searches for specic contact which has occurrence of argument in name or phone number
showPeoplePicker(callback)
shows modal dialog with contents of address book, when phone selected callback functions will be called with 3 parameters: name, phone number and e-mail.
Example:
var addressBook = new NKContact(); document.write("<a href=\"#\" onClick=\"addressBook.showPeoplePicker ('personSelected()')\">Show People Picker</a>"); function personSelected(name, phone, email) { NKAlert("Person selected", "Name: "+name+" phone: "+phone+" email: "+email); }
39
NimbleKit SDK!
v. 1.9.7
NKAudioPlayer
Overview
Used to play audio les bundled in the application
loadFile(leName)
Loads the content of le specied by leName parameter and prepares it to play
loadFileFromDocuments(leName)
Loads the content of le and prepares it to play, looking for given le name in documents folder
play()
starts to play loaded le
stop()
stops currently playing audio
pause()
pauses currently played audio
resume()
resumes playback from paused state
getDurationInSeconds()
returns integer value specifying duration in seconds of the loaded audio
setPositionInSeconds(seconds)
sets playback position in seconds
getCurrentPositionInSeconds()
returns current position measured in seconds
setPlayingFinishedCallback(callback)
Used to get information about when playback nished
Parameters:
setLoopMode(isInLoop)
sets if player should repeat loaded le, can take argument yes, no, 1 and 0
setVolume(volume)
sets current volume for player, parameter has to be in range [0..100]
dispose()
disposes resources allocated for player
Copyright VolnaTech 2009-2010! 40
NimbleKit SDK!
v. 1.9.7
setIgnoreLock(isIgnored)
if this function is set to yes then application will still continue to play even if user locked the phone. Available in NimbleKit 1.7 or newer Example of controlling one player from different pages page1.html:
var player1 = new NKAudioPlayer(); player1.loadFile("music.mp3"); var settings = new NKSettings(); settings.setValueForKey(player_id,playerID); //save player1.id in NKSettings
page2.html:
var player2 = new NKAudioPlayer(); player2.dispose(); // release second's player resources as we will use resources of the first player var settings = new NKSettings(); player2.id = settings.getValueForKey(playerID); player2.play(); // launch play of the first player
41
NimbleKit SDK!
v. 1.9.7
NKVideoPlayer
Overview
Class is used to play video les in iPhone compatible format. Be advised that supported formats are: H.264 Baseline Prole Level 3.0 video, up to 640 x 480 at 30 fps. Note that B ! frames are not supported in the Baseline prole. MPEG-4 Part 2 video (Simple Prole) Also this class can open and play audio les including AAC-LC audio at up to 48 kHz.
openURL(url)
opens video stream from URL
openFileName(leName)
opens video le stored in application bundle
play()
starts video playback
stop()
stops current video playback
42
NimbleKit SDK!
v. 1.9.7
NKSystemVolumeControl
Overview
This class is used to control iOS sound volume
init(x, y, width)
initializes and shows UI control to control system sound volume, looks similar to progress bar. Can be called multiple times to reposition control if needed.
43
NimbleKit SDK!
v. 1.9.7
NKAlertSheet
Overview
This class is used to conrm user destructive actions or provide a choice between different actions.
init(callback)
initializes alert sheet with callback, which to be called when any button clicked on alert sheet. The function callback has to take one parameter which is an index of clicked button.
addButtonWithTitle(title)
adds button to alert sheet with specied title
setStyle(style)
sets style of the alert sheet, by default style is automatic, possible values are: black, blacktranslucent and automatic.
setTitle(title)
sets the title of the alert sheet.
setRedButtonIndex(index)
sets the index of button to be shown as red button, this button has to have destructive sense and used only when user is going to loose data or application closed, etc.
setBlackButtonIndex(index)
sets the index of button to be shown as black button which used as cancel button in most of the dialogs.
Example: function actionSheetButtonPressed(number) { ! NKAlert("Button pressed", number); } function showActionSheet() { ! var sheet = new NKAlertSheet(); ! sheet.init("actionSheetButtonPressed"); ! sheet.addButtonWithTitle("ok"); ! sheet.addButtonWithTitle("no way"); ! sheet.addButtonWithTitle("I don't know"); ! sheet.setStyle("black"); ! sheet.setTitle("Make your choice"); ! sheet.show(); }
Copyright VolnaTech 2009-2010! 44
NimbleKit SDK!
v. 1.9.7
45
NimbleKit SDK!
v. 1.9.7
NKFile
Overview
Used to read les bundled in the application
open(leName)
Opens le with given lename for reading, should be just name and le extension, returned value is either 1 or 0 identifying if le was opened.
openFromDocuments(lename)
Opens le with given lename for reading which located in documents folder, should be just name and le extension, returned value is either 1 or 0 identifying if le was opened.
read(position, length)
Returns buffer of bytes read from given position in the le and with given length
position()
Returns the value identifying current offset in the le
close()
Closes le and frees all resources allocated for it
size()
Returns size of the opened le in bytes
deleteFile()
deletes current le, can only be used on les opened from documents folder. Bundled les are read-only.
Discussion (possible crashes): NKFile should be used carefully, because all methods of this class are synchronous and may result main thread to freeze for more then 5 seconds, which is time maximum allowed for javascript function to run. In case if 5 seconds limit reached unpredictable situations can appear. Please refer to Troubleshooting section for solution.
46
NimbleKit SDK!
v. 1.9.7
NKSettings
Overview
Used to save application settings
getValueForKey(key)
Retrieves saved value for specied key (can be javascript object from v1.6.2)
setValueForKey(value, key)
Saves value in application settings for specied key (can take any object value staring from v1.6.2)
Example:
In this example we use NKSettings class to save/retrieve username from application settings. var settings = new NKSettings(); settings.setValueForKey("UserName", "user"); var username = settings.getValueForKey("user");
Discussion (possible crashes): To be safe it is better to call settings before creating interface, as NKSettings methods work synchronously and they would wait until all all interface elements loaded which can cause javascript function to be canceled as it takes too long.
47
NimbleKit SDK!
v. 1.9.7
NKFileDownloader
Overview
This class is used to download les from internet to documents folder (later those les can be opened with NKFile).
openURL(url)
Initializes current downloader with url
start(leName)
Starts asynchronous download process.
lename - name of the output le to be created in documents folder
stop()
Stops download
getProgress()
Returns percentage of downloaded data or -1 if error occured Example:
var download = new NKFileDownloader(); download.openURL("http://www.nimblekit.com/nimblekit.dmg"); download.start("nimblekit.dmg"); setTimeout(updateProgress, 1000); function updateProgress() { var progress = download.getProgress(); if (progress == -1) { NKLog("Could not download file"); } else { NKLog("downloaded: "+progress); if (download.getProgress()<100) setTimeout(updateProgress, 1000); } }
48
NimbleKit SDK!
v. 1.9.7
NKSQLite
Overview
This class is used to access database and use sqlite databases. NKSQLite is global singleton class so you can access opened database from any page, but if you open new one, previous will be closed automatically. So its preferable to use 1 database with multiple tables to open/close database only once.
openDatabase(name, rewrite)
opens database with given name and rewrites it if rewrite is set to 1 or yes.
Discussion:
SQLite database le is stored in application bundle, but the location is not writable so when we call openDatabase NimbleKit tries to open database with this name from writable location in documents folder of iPhone, it there is no such le - NimbleKit copies it from bundle to writable location and opens again. So once you opened your database on current device, database le in bundle wont be accessed, but of course if you changed tables or put new data in initial table you can put rewrite variable to 1 or yes to rewrite database at writable location.
executeSQL(query)
executes standard SQL query, (i.e. SELECT * FROM mytable)
getResults()
returns the result as javascript array of dictionaries (This API was redesigned in v1.7, please update old code)
closeDatabase()
closes current database
Example:
var database = new NKSQLite(); database.openDatabase("nk.sqlite", "no"); database.executeSQL("CREATE TABLE todo(pk INTEGER PRIMARY KEY, text VARCHAR(25), priority INTEGER, complete BOOLEAN)"); database.executeSQL("INSERT INTO todo(text,priority,complete) VALUES('Take out the trash',3,0)"); database.executeSQL("INSERT INTO todo(text,priority,complete) VALUES('Do Computer Science homework',1,0)"); database.executeSQL("INSERT INTO todo(text,priority,complete) VALUES('Learn Objective C',1,0)"); database.executeSQL("INSERT INTO todo(text,priority,complete) VALUES('DIGG this tutorial',2,0)"); database.executeSQL("SELECT * FROM todo"); results = database.getResults(); for (i=0; i<results.length; i++) { ! document.body.innerHTML+="<p>"+results[i].priority+" | "+results[i].complete+" | "+results[i].text+"</p>"; }
database.closeDatabase();
49
NimbleKit SDK!
v. 1.9.7
NKMapView
Overview init(x,y,width,height)
initializes map view with given width, height and coordinates on webview
show()
shows initialized map view
hide()
hides initialized map view
showUserlocation()
triggers core location services to track user location and show it on the map, can take parameters "yes" or "no"
setMapType()
sets the map type, can take parameters "standard", "satellite", "hybrid"
getUserLocation(callback)
retrieves current user location, takes callback parameter of format callback (newLocation), new location returned as callback argument
isUserLocationUpdating()
indicates if CoreLocation is turned on to update user location, returns "1" or "0"
The amount of north-to-south distance (measured in degrees) to use for the span. Unlike longitudinal distances, which vary based on the latitude, one degree of latitude is approximately 111 kilometers (69 miles) at all times.
longitudeDelta
The amount of east-to-west distance (measured in degrees) to use for the span. The number of kilometers spanned by a longitude range varies based on the current latitude. For example, one degree of longitude spans a distance of approximately 111 kilometers (69 milies) at the equator but shrinks to 0 kilometers at the poles.
50
NimbleKit SDK!
v. 1.9.7
selectAnnotation(title)
selects annotation with the title specied when annotation was added, do not use this method directly after annotation was added as it has no time to initialize, use setTimeout function to select annotation after a small delay like half a second.
setDelegateCallback(callback)
sets delegate callback to be called when map is loading, loaded or failed to load. The callback format is following "callback(state)", where state can take following values: 0 for loading, 1 for loaded and -1 if loading failed
clearAnnotations()
removes all annotations added to the map previously
getDisplayRegion()
returns display region which is visible to the user at the moment, the region returned as a string with 4 components divided by comma: center longitude, center latitude, span longitude delta and span latitude delta, for example: 102.122,34.65,12.1,2.06
Implement this callback on the page where NKMapView was created and it will be called automatically every time user touches the map returning latitude and longitude as callback parameters. If you dont need user input just ignore this callback and dont implement it. Example:
var map = new NKMapView(); map.init(0, 100, 320, 460); lat = 50; lon = 30; map.setDisplayRegion(lat, lon, 0.007435, 0.003130); map.showUserLocation("YES"); map.addAnnotation(lat, lon, "Here", "subtitle"); map.show(); setTimeout(selectAnnotation, 500); //wait for half second function selectAnnotation() { ! map.selectAnnotation('Here'); }
Example 2: Use NKMapView as gps without showing map on screen, we check here for new coordinates every second until they are obtained
Copyright VolnaTech 2009-2010! 51
NimbleKit SDK!
var oldLocation = "0.000000 0.000000 0.000000 0.000000"; var mapView = new NKMapView(); mapView.init(0, 0, 320, 420); mapView.showUserLocation("YES"); checkIfUpdated(); function checkIfUpdated() { mapView.getUserLocation("alertLocation"); } function alertLocation(newLocation){ ! if (newLocation != oldLocation){ ! ! oldLocation = newLocation; ! ! var location = new Array(); ! ! location = newLocation.split(" "); // now location is an array with 4 elements: x, y, precision and speed ! } ! else ! ! setTimeout(checkIfUpdated, 1000); }
v. 1.9.7
52
NimbleKit SDK!
v. 1.9.7
NKAppStore
Overview
This class is used to make in-app purchases
getAvailableProducts(callback, productIDs)
this function returns it's value via callback only when products are requested and updated via internet.
callback
name of the function to be called when product list is updated, function prototype is following callback(productsCount)
productIDs
the list of product identiers for the products you wish to retrieve descriptions of, it needs to be in format of a string where all identiers separated by blank space, for example "my.company.prod1 my.company.prod2 my.company.prod3" will try to retrieve 3 products with given IDs.
requestInfoForProductAtIndex(index, callback)
index
callback to be called with product information, format of callback is following: callback (title,description,productID,price)
buyProductWithID(identicator, callback)
attempts to buy selected product
identicator
unique product ID
callback
a function name, which will notify if transaction was successful, will return either unique product ID or -1 if transaction failed, format is following callback(result).
53
NimbleKit SDK!
v. 1.9.7
NKPasteboard
Overview
this class is used to work with pasteboard
getString()
returns a string which was previously copied to clipboard
setString(value)
copies given string value to clipboard
getURL()
returns url previously copied to clipboard
setURL(value)
copies given string value of url to clipboard
54
NimbleKit SDK!
v. 1.9.7
NKImage
Overview
NKImage is a class that used to represent, modify and save images. It is used by various classes as input or output, for example when you pick picture from camera it is an output object, which can be used as input object for NKImageView.
loadURL(url)
load image from specied URL
loadFromDocuments(leName)
loads named image from documents folder
loadFromBundle(leName)
loads named image from application bundle
loadFromBase64(base64String)
loads image data from base64 encoded string
getBase64(compression)
returns base64 representation of jpeg image, compression is used to specify output quality (and size) can take values [0..1]
setSize(width, height)
resizes image to gives rectangle
saveToLibrary()
saves valid image object in iPhones photo library.
saveToDocuments(name)
saves the image as a le in the documents folder with specied name
getSize()
return current size of the image in format of the string where width and height are divided by comma, for example 800,600
rotate(degrees)
rotates the image with and angle specied in degrees parameter. Available in NimbleKit 1.7 or newer.
55
NimbleKit SDK!
v. 1.9.7
NKMailComposer
Overview
Composer is used to send e-mail messages without leaving the application and having content, subject and recipient pre-lled.
show()
shows modal mail composer on top of application pages, call this after you already lled all elds you need (like subject, body or recipient).
setSubject(subject)
sets mail composer subject
setRecipient(recipients)
sets recipients as e-mail addresses, can take many addresses at once divided by comma.
setCC(value)
sets carbon copy addresses divided by comma
setBCC(value)
sets blind carbon copy addresses divided by comma
setBody(body)
sets the body of the message.
addImage(image)
adds image to composed e-mail, can be called multiple times to add many pictures. Image parameter is an instance of NKImage class.
Example:
function showComposer() { ! var composer = new NKMailComposer(); ! composer.setRecipient("a.voloshyn@gmail.com, voloshyn@me.com"); ! composer.setSubject("subject");! ! composer.setBody("message body!"); ! composer.show(); }
56
NimbleKit SDK!
v. 1.9.7
NKSMSComposer
Overview
This class is used send SMS messages with the ability to compose or use precomposed messages as message body.
setRecipient(value)
sets recipients as phone numbers, can take many phone numbers at once divided by comma.
setBody(text)
sets the text of SMS body
show()
presents mail composer UI as modal view controller. Class Available in NimbleKit 1.9.4 or newer
57
NimbleKit SDK!
v. 1.9.7
NKPopoverController
Overview
You use popovers to present information temporarily but in a way that does not take over the entire screen like a modal view does
init(contentPage)
initializes NKPopoverController with a page that represents popovers content, can be called again in order to change the page in already initialized controller
hide()
hides initialized and shown on the screen popover controller.
setContentSize(width, height)
resizes content size of the popover controller. Can be called in any state when controller is hidden or shown (when shown it will resize animated).
Sample usage:
! ! ! ! var popover = new NKPopoverController(); popover.init("popoverContent.html"); popover.setContentSize(100, 200); popover.show(200,300,100,100);
Class Available in NimbleKit 1.9.4 or newer and requires iPad, any calls to this class are ignored on non-iPad device.
58
NimbleKit SDK!
v. 1.9.7
NKWebView
Overview
WebView native control which allows you to load external URLs and show its content in your application.
show()
shows initialized WebView (initially all native controls are hidden)
hide()
hides initialized WebView
loadURL(url)
loads given URL
setScalesToFit(isScaled)
sets if WebView should scale page to t or display the page in its original size
loadHTML(html, baseURL)
directly loads specied HTML code using baseURL as base URL for the content
loadFromBundle(name)
loads html le from application bundle
goBack()
loads previous page from history
goForward()
loads next page from history
reload()
reloads current page
setOnFinishCallback(callback)
sets the callback which will be called when the page is loaded in the current web view. Callback is a string function name to be called.
setDetectsPhoneNumbers(detectionAllowed)
enables/disables telephone numbers detection, can take values yes and no
Example:
var webView = new NKWebView;
59
NimbleKit SDK!
webView.init(0,0,300,300); webView.loadURL("http://nimblekit.com/"); webView.setScalesToFit("yes"); webView.setOnFinishCallback("testcallback"); webView.show();
v. 1.9.7
60
NimbleKit SDK!
v. 1.9.7
NimbleKit functions
NKGetUniqueIdentier()
Returns devices unique identier based on hardware serial number.
NKGetDeviceType()
returns device type, possible values:
iPhone 1G iPhone 3G iPhone 3GS iPhone 4 iPod Touch 1G iPod Touch 2G iPod Touch 3G iPod Touch 4G iPad iPhone Simulator
NKSetPageOpaque(page, isOpaque)
Controls opaque state for specied page. isOpaque can be yes, no, 1 and 0. Set opaque to no when you want the page to be transparent. Available in NimbleKit 1.9.4 or newer
NKSetBackground(leName)
sets background behind the web page (visible if the page is transparent of user bounces the page)
NKIsInternetAvailableViaCellularNetwork
Returned value can be either 1 or 0 which represents if internet access available using Cellular data network.
NKIsInternetAvailableViaWi
Returned value can be either 1 or 0 which represents if internet access available using Wi-Fi network.
NKAlert(title, message)
Shows alert with provided title and message
NKMoveToPageAnimated(pageName, animation)
Used to navigate between pages without navigation controller
Parameters:
pageName - name of the html page to move, can accept parameters (i.e. next.html? id=25&name=user), see NKGetParameter function for retrieving parameters. animation - name of the animation to use, currently supported animations: Fade, PushLeft, PushRight, FastPushRight, FastPushLeft, FlipLeft, FlipRight. In version 1.7 added slidedown and slideup animations. In version 1.9 added curlup and curldown animations.
Copyright VolnaTech 2009-2010! 61
NimbleKit SDK!
v. 1.9.7
NKOpenURLInSafari(url)
opens given URL in mobile Safari browser
NKOpenDocument(name, source)
Opens the document in the applications which registered to support that kind of document (i.e. pdf in iBooks or GoodReader, etc).
name - name of the le or documents URL source - species where to look for your document, can take 3 values: NKBundle, NKDocuments, NKURL
NKStartPreloadingPage(pageName)
this function preloads the page with given name. Please be advised that loading many pages simultaneously can cause application to start very slow or greatly decrease performance. It is recommended to preload only pages critical to be preloaded. Example:
! NKStartPreloadingPage("page2.html");
NKReloadPage(pageName)
Reload page specied (useful if you want tab content reloaded)
NKGetLibraryVersion()
returns library version as string, for instance 1.6.3
NKGetParameter(name)
retrieves parameter passed as GET variable to the page, for instance navcontroller.gotoPage(page.html?myVar=hello); in page page.html you can use NKGetParameter(myVar); to retrieve the value of variable.
NKLog(message)
logs provided message in the application run log or iPhones console log, used for debug purposes only. Available in NimbleKit 1.7 or newer
62
NimbleKit SDK!
v. 1.9.7
NKExecuteJavascriptOnPage(jscode, pagename)
executes provided javascript code on specied page
NKGetAppVersion()
returns the version of the application (specied in info.plist le or set in Xcodes target properties) Available in NimbleKit 1.8.3 or newer
NKPreloadPage(pageName, callback)
starts asynchronous preloading of the page, taking as parameters name of the page to preload and a callback, which is a javascript function name, to be called when preloading is nished.
63
NimbleKit SDK!
v. 1.9.7
NKNativeControlRotate(control, degrees)
rotates native control (like NKTextField, NKButton, etc) with given angle specied in degrees.
NKSetControlAutoresizingMask(control, mask)
sets the autoresizing mask of native control, which controls automatic autoresizing on device rotation control - control for which you want to set autoresizing mask mask - autoresizing mask. Can be one of or any combination of following constants.
NKControlAutoresizingNone
The view does not resize. NKControlAutoresizingFlexibleLeftMargin
The view resizes by expanding or shrinking in the direction of the left margin. NKControlAutoresizingFlexibleWidth
The view resizes by expanding or shrinking its width. NKControlAutoresizingFlexibleRightMargin
The view resizes by expanding or shrinking in the direction of the right margin. NKControlAutoresizingFlexibleTopMargin
The view resizes by expanding or shrinking in the direction of the top margin. NKControlAutoresizingFlexibleHeight
The view resizes by expanding or shrinking its height. NKControlAutoresizingFlexibleBottomMargin
The view resizes by expanding or shrinking in the direction of the bottom margin.
Example:
function createToolBar() { ! var toolbar = new NKToolBar(); ! toolbar.init(0); ! NKSetControlAutoresizingMask(toolbar, NKControlAutoresizingFlexibleWidth | NKControlAutoresizingFlexibleBottomMargin) ! toolbar.show(); }
this will make tab bar with exible width and will make it glue to the top of the screen (as bottom margin is exible and top margin is not).
NKNativeControlSetAlpha(control, alpha)
sets the transparency of the native xed iPhone control (like NKButton, NKSlider, etc) using provided alpha, value must be in range [0..1]. Available in NimbleKit 1.9 or newer
NKNativeControlEnable(control, isEnabled)
Controls enabled/disabled state of the native control. isEnabled can take values: yes, no, 1 and 0. Available in NimbleKit 1.9.4 or newer
64
NimbleKit SDK!
v. 1.9.7
NKControlSetBackgroundColor(control, r, g, b, a)
Sets native controls background color using 4 color components. All components are values in range [0..255]
65
NimbleKit SDK!
v. 1.9.7
NKUpdateLocation(callback)
- callback is the name of a function callback to be called when device nished updating location, function has to take 5 parameters: latitude, longitude, precision, distance and error (0 returned if no error).
Usage:
NKUpdateLocation("locationUpdated"); function locationUpdated(x, y, precise, moved, error) { NKAlert("Location updated", "x: "+x+" y: "+y+" precision: "+precise+" moved: "+moved); }
66
NimbleKit SDK!
v. 1.9.7
NKTakePicture(callback, source)
This function pops up standard image picking dialog or photo camera dialog to choose/ take picture
Parameters:
- callback is a name os function to be called when user picked picture, has to have 1 parameter to receive base64 encoded image is jpeg format. - source is a name of source from which to take image, can take values: PhotoLibrary, SavedPhotoAlbum and Camera. Please be advices that you can not take pictures from camera on iPhone Simulator as there is none. This API is deprecated in NimbleKit 1.7, use NKPickImageObject instead
Example:
<center> <div id="mypicture"></div> </center> <script type="text/javascript"> NKTakePicture('picturePicked', 'photolibrary'); function picturePicked(imageBase64) { var node = document.getElementById("mypicture"); node.innerHTML = "<img height=\"300\" width=\"200\" src=\""+"data:image/ jpg;base64,\n"+imageBase64+"\"/>"; } </script>
- callback is a name os function to be called when user picked picture, has to have 1 parameter to receive NKImage object. - source is a name of source from which to take image, can take values: PhotoLibrary, SavedPhotoAlbum and Camera. Please be advices that you can not take pictures from camera on iPhone Simulator as there is none. - x, y, width, height are the parameters used for iPad implementation only and specify the frame where popover controller must point to. These parameters are optional.
Example:
NKPickImageObject('picturePicked', 'camera'); function picturePicked(imageObj) { ! imageView = new NKImageView(); ! imageView.init(10, 10, 100, 100); ! imageView.setImageObject(imageObj); ! imageView.show(); }
NimbleKit SDK!
v. 1.9.7
Orientation support
iPhone application can change orientation, this sections describes how use this feature.
NKIsPageSupportsAutoOrientation()
This function must be implemented and return no if you dont want to some specic page to have orientations supported. By default auto orientation is supported and possible orientations are read from your application plist le (in xcode4 those can be set in editor graphically)
Example:
function NKIsPageSupportsAutoOrientation() { return "no"; }
pageWillRotate(degree)
implement this function in order to receive information when iPhone is about to start orientation change to orientation specied in parameter.
Degree - can take 4 values:
0 - portrait -90 - landscape left 90 - landscape right 180 - portrait upside down
pageDidRotate()
implement this function to receive notication when orientation transition is complete
68
NimbleKit SDK!
v. 1.9.7
Application Events
OnApplicationQuit()
This callback is called right after application started quitting. Please do not use any alerts or similar UI actions as till the moment this function called there will be no application UI on the screen. Callback is called on every page, be sure not to overwrite many times your settings.
Example:
function OnApplicationQuit() { var settings = new NKSettings(); settings.setValueForKey("saved!!!", "isSaved"); }
OnApplicationPause()
This callback is called when application goes to background mode. You have to save your settings in this call back as application can be terminated by OS while in background without notication. Please do not use any alerts or similar UI actions as till the moment this function called there will be no application UI on the screen. Callback is called on every page, be sure not to overwrite many times your settings.
OnApplicationResume()
This callback is called when application returns to foreground mode from background mode.
onPageShown(caller)
This callback is called right before page is shown (but is fully loaded).
caller - the object which moved page in front, can be tab_controller, nav_controller or
window
onPageHidden()
this callback is called when page lost focus. When UI is constructed can be called multiple times as if you create navigation controller page will be removed from the window and placed in navigation controller, so this function will be called when this happens.
69
NimbleKit SDK!
v. 1.9.7
FAQ
1. How to add fullscreen company logo on application start?
You need to add le Default.png image to the project, it will be used automatically ! by iPhone OS
2. How to set image behind page so it is visible when user scrolls page?
You need to add le nk_background.png image to the project, it will be used automatically by NimbleKit engine
70
NimbleKit SDK!
v. 1.9.7
Troubleshooting
Overview
This section describes common problems and solutions for them
Threading
10 seconds javascript limit There is a limit of 10 seconds for all javascript functions to run. Some NimbleKit functions are asynchronous and some of them synchronous, main problem here is even if you use synchronous function which runs for less then 5 seconds it still can be executed for more then 5 seconds if before there was a call to asynchronous functions which are still executing, synchronous function will have to wait for them to nish. For instance all functions related to interface elements are asynchronous and used during loading time to build interface. All of those functions will return immediately, but in background will still work, which means if you call something like le reading during load time you can end up with crash because all le operations are synchronous and it will wait for all background functions to nish. Solution to this problem is simple, load all interface elements in <head> section and if you need to do some synchronous operations on load time move them to separate function and specify it to onLoad property of <body> section, so its called after all interface is loaded.
71