archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • IOS 9 Database Implementation using SQLite - Techotopia
    sqlite insert into contacts name address phone values Bill Smith 123 Main Street California 123 555 2323 sqlite insert into contacts name address phone values Mike Parks 10 Upping Street Idaho 444 444 1212 To retrieve all rows from a table sqlite select from contacts 1 Bill Smith 123 Main Street California 123 555 2323 2 Mike Parks 10 Upping Street Idaho 444 444 1212 To extract a row that meets specific criteria sqlite select from contacts where name Mike Parks 2 Mike Parks 10 Upping Street Idaho 444 444 1212 To exit from the sqlite3 interactive environment sqlite exit When running an iOS application in the iOS Simulator environment any database files will be created on the file system of the computer on which the simulator is running This has the advantage that you can navigate to the location of the database file load it into the sqlite3 interactive tool and perform tasks on the data to identify possible problems occurring in the application code If for example an application creates a database file named contacts db in its documents directory the file will be located on the host system in the following folder Users user Library Developer CoreSimulator Devices simulator id data Containers Data Application id Documents Where user is the login name of the user logged into the Mac OS X system simulator id is the id of the simulator session and id is the unique ID of the application Preparing an iOS Application Project for SQLite Integration By default the Xcode environment does not assume that you will be including SQLite in your application When developing SQLite based applications a few additional steps are required to ensure the code will compile when the application is built First the project needs to be configured to include the libsqlite3 tbd dynamic library during the link phase of the build process To achieve this select the target entry in the Xcode project navigator the top entry with the product name to display the summary information Select the Build Phases tab to display the build information The Link Binary with Libraries section lists the libraries and frameworks already included in the project To add another library or framework click on the button to display the full list From this list select the required item in this case libsqlite3 tbd and click Add SQLite Swift and Wrappers As previously discussed SQLite is written in the C programming language Whilst it was still possible to use the C based SQLite API from within Objective C code with relative ease this is not the case when programming in Swift without dealing with complex issues when bridging the gap between C and Swift A common solution to this dilemma involves the use of a SQLite wrapper A number of wrappers are now available for this purpose many of which show considerable potential For the purposes of this book however we will be working with the FMDB wrapper Although this is essentially an Objective C

    Original URL path: http://www.techotopia.com/index.php/IOS_9_Database_Implementation_using_SQLite (2016-02-13)
    Open archived version from archive


  • An Example SQLite based iOS 9 Application using Swift and FMDB - Techotopia
    from the Object Library View Utilities Show Object Library onto the view canvas and edit properties so that the layout appears as illustrated in Figure 46 4 Figure 46 4 Before proceeding stretch the status label located above the two buttons so that it is the same width as the combined labels and text field views and change the text alignment in the Attributes Inspector so that it is centered Finally edit the label and remove the word Label so that it is blank Select the top most text field object in the view canvas display the Assistant Editor panel and verify that the editor is displaying the contents of the ViewController swift file Ctrl click on the text field object again and drag to a position just below the class declaration line in the Assistant Editor Release the line and in the resulting connection dialog establish an outlet connection named name Repeat the above steps to establish outlet connections for the remaining text fields and the label object to properties named address phone and status respectively Ctrl click on the Save button object and drag the line to the area immediately beneath the existing viewDidLoad method in the Assistant Editor panel Release the line and within the resulting connection dialog establish an Action method on the Touch Up Inside event configured to call a method named saveData Repeat this step to create an action connection from the Find button to a method named findContact Close the Assistant Editor panel select the ViewController swift file and add a variable to store a reference to the database path class ViewController UIViewController IBOutlet weak var name UITextField IBOutlet weak var address UITextField IBOutlet weak var phone UITextField IBOutlet weak var status UILabel var databasePath NSString override func viewDidLoad super viewDidLoad IBAction func saveData sender AnyObject IBAction func findContact sender AnyObject Creating the Database and Table When the application is launched it will need to check whether the database file already exists and if not create both the database file and a table within the database in which to store the contact information entered by the user The code to perform this task can be placed in the viewDidLoad method of our view controller class Select the ViewController swift file scroll down to the viewDidLoad method and modify it as follows override func viewDidLoad super viewDidLoad let filemgr NSFileManager defaultManager let dirPaths filemgr URLsForDirectory DocumentDirectory inDomains UserDomainMask databasePath dirPaths 0 URLByAppendingPathComponent contacts db path if filemgr fileExistsAtPath databasePath as String let contactDB FMDatabase path databasePath as String if contactDB nil print Error contactDB lastErrorMessage if contactDB open let sql stmt CREATE TABLE IF NOT EXISTS CONTACTS ID INTEGER PRIMARY KEY AUTOINCREMENT NAME TEXT ADDRESS TEXT PHONE TEXT if contactDB executeStatements sql stmt print Error contactDB lastErrorMessage contactDB close else print Error contactDB lastErrorMessage The code in the above method performs the following tasks Identifies the application s Documents directory and constructs a path to the contacts db database file Checks if the database

    Original URL path: http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_9_Application_using_Swift_and_FMDB (2016-02-13)
    Open archived version from archive

  • Working with iOS 9 Databases using Core Data - Techotopia
    than one persistent object store When multiple stores are required the coordinator presents these stores to the upper layers of the Core Data stack as a single store Persistent Object Store The term persistent object store refers to the underlying storage environment in which data are stored when using Core Data Core Data supports three disk based and one memory based persistent store Disk based options consist of SQLite XML and binary By default the iOS SDK will use SQLite as the persistent store In practice the type of store being used is transparent to you as the developer Regardless of your choice of persistent store your code will make the same calls to the same Core Data APIs to manage the data objects required by your application Defining an Entity Description Entity descriptions may be defined from within the Xcode environment When a new project is created with the option to include Core Data a template file will be created named projectname xcdatamodeld Selecting this file in the Xcode project navigator panel will load the model into the entity editing environment as illustrated in Figure 47 2 Figure 47 2 Create a new entity by clicking on the Add Entity button located in the bottom panel The new entity will appear as a text box in the Entities list By default this will be named Entity Double click on this name to change it To add attributes to the entity click on the Add Attribute button located in the bottom panel or use the button located beneath the Attributes section In the Attributes panel name the attribute and specify the type and any other options that are required eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Repeat the above steps to add more attributes and additional entities The Xcode entity environment also allows relationships to be established between entities Assume for example two entities named Contacts and Sales In order to establish a relationship between the two tables select the Contacts entity and click on the button beneath the Relationships panel In the detail panel name the relationship specify the destination as the Sales entity and any other options that are required for the relationship Once the relationship has been established it is perhaps best viewed graphically by selecting the Table Graph option in the Editor Style control located in the bottom panel Figure 47 3 As demonstrated Xcode makes the process of entity description creation fairly straightforward Whilst a detailed overview of the process is beyond the scope of this book there are many other resources available that are dedicated to the subject Obtaining the Managed Object Context Since many of the Core Data methods require the managed object context as an argument the next step after defining entity descriptions often involves obtaining a reference to the context

    Original URL path: http://www.techotopia.com/index.php/Working_with_iOS_9_Databases_using_Core_Data (2016-02-13)
    Open archived version from archive

  • An iOS 9 Core Data Tutorial - Techotopia
    the three data property fields import Foundation import CoreData extension Contacts NSManaged var name String NSManaged var address String NSManaged var phone String eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Designing the User Interface With the entity defined now is a good time to design the user interface and establish the outlet and action connections Select the Main storyboard file to begin the design work The user interface and corresponding connections used in this tutorial are the same as those in previous data persistence chapters The completed view should once again appear as outlined in Figure 48 5 note that objects may be cut and pasted from the previous Database project to save time in designing the user interface layout Figure 48 5 Before proceeding stretch the status label located above the two buttons so that it covers most of the width of the view and configure the alignment attribute so that the text is centered Finally edit the label and remove the word Label so that it is blank Select the top most text field object in the view canvas display the Assistant Editor panel and verify that the editor is displaying the contents of the ViewController swift file Ctrl click on the text field object again and drag to a position just below the class declaration line in the Assistant Editor Release the line and in the resulting connection dialog establish an outlet connection named name Repeat the above steps to establish outlet connections for the remaining text fields and the label object to properties named address phone and status respectively Ctrl click on the Save button object and drag the line to the area immediately beneath the viewDidLoad method in the Assistant Editor panel Release the line and within the resulting connection dialog establish an Action method on the Touch Up Inside event configured to call a method named saveContact Repeat this step to create an action connection from the Find button to a method named findContact Accessing the Managed Object Context In order to store and retrieve data using Core Data a reference to the application delegate s managed object context is required Within the ViewController swift file import the CoreData Framework and add a variable in which to store this reference as follows import UIKit import CoreData class ViewController UIViewController let managedObjectContext UIApplication sharedApplication delegate as AppDelegate managedObjectContext IBOutlet weak var name UITextField IBOutlet weak var address UITextField IBOutlet weak var phone UITextField IBOutlet weak var status UILabel Saving Data to the Persistent Store using Core Data When the user touches the Save button the saveContact method is called It is within this method therefore that we must implement the code to create and store managed objects containing the data entered by the user Select the ViewController swift file scroll down to the template

    Original URL path: http://www.techotopia.com/index.php/An_iOS_9_Core_Data_Tutorial (2016-02-13)
    Open archived version from archive

  • An Introduction to CloudKit Data Storage on iOS 9 - Techotopia
    to and from the iCloud servers In most cases therefore a call to CloudKit API methods will require that a completion handler be provided This handler code will then be executed when the corresponding operation completes and passed results data where appropriate or an error object in the event of a failure Given the asynchronous nature of CloudKit operations it is important to implement robust error handling within the completion handler The steps involved in creating updating querying and deleting records will be covered in greater detail in the next chapter entitled An iOS 9 CloudKit Example The overall concept of an application cloud container private and public databases and records can be visualized as illustrated in Figure 49 1 Figure 49 1 CloudKit Record IDs Each CloudKit record has associated with it a unique record ID represented by the CKRecordID class If a record ID is not specified when a record is first created one is provided for it automatically by the CloudKit framework CloudKit References CloudKit references are implemented using the CKReference class and provide a way to establish relationships between different records in a database A reference is established by creating a CKReference instance for an originating record and assigning to it the record to which the relationship is to be targeted The CKReference object is then stored in the originating record as a key value pair field A single record can contain multiple references to other records Once a record is configured with a reference pointing to a target record that record is said to be owned by the target record When the owner record is deleted all records that refer to it are also deleted and so on down the chain of references a concept referred to as cascading deletes CloudKit Assets In addition to data CloudKit may also be used to store larger assets such as audio or video files large documents binary data files or images These assets are stored within CKAsset instances Assets can only be stored as part of a record and it is not possible to directly store an asset in a cloud database Once created an asset is added to a record as just another key value field pair The following code for example demonstrates the addition of an image asset to a record let imageAsset CKAsset fileURL imageURL let myRecord CKRecord recordType Vacations myRecord setObject London forKey city myRecord setObject imageAsset forKey photo At the time of writing individual CloudKit assets are limited in size to 250Mb Record Zones CloudKit record zones CKRecordZone provide a mechanism for relating groups of records within a private database Unless a record zone is specified when a record is saved to the cloud it is placed in the default zone of the target database Custom zones can be added to private databases and used to organize related records and perform tasks such as writing to multiple records simultaneously in a single transaction Each record zone has associated with it a unique record

    Original URL path: http://www.techotopia.com/index.php/An_Introduction_to_CloudKit_Data_Storage_on_iOS_9 (2016-02-13)
    Open archived version from archive

  • An iOS 9 CloudKit Example - Techotopia
    interface Within the ViewController swift file override the touchesBegan method to hide the keyboard when the user taps the background view of the user interface override func touchesBegan touches Set UITouch withEvent event UIEvent addressField endEditing true commentsField endEditing true Implementing the selectPhoto method The purpose of the Photo button in the toolbar is to allow the user to include a photo in the database record Begin by declaring that the View Controller class implements the UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols then locate the template selectPhoto action method within the ViewController swift file and implement the code as follows class ViewController UIViewController UIImagePickerControllerDelegate UINavigationControllerDelegate IBAction func selectPhoto sender AnyObject let imagePicker UIImagePickerController imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceType PhotoLibrary imagePicker mediaTypes kUTTypeImage as String self presentViewController imagePicker animated true completion nil When executed the code will cause the image picker view controller to be displayed from which the user can select a photo from the photo library on the device to be stored along with the current record in the application s public cloud database The final step in the photo selection process is to implement the delegate methods which will be called when the user has either made a photo selection or cancels the selection process func imagePickerController picker UIImagePickerController didFinishPickingMediaWithInfo info String AnyObject self dismissViewControllerAnimated true completion nil let image info UIImagePickerControllerOriginalImage as UIImage imageView image image photoURL saveImageToFile image func imagePickerControllerDidCancel picker UIImagePickerController self dismissViewControllerAnimated true completion nil In both cases the image picker view controller is dismissed from view In the case of a photo being selected the image is displayed within the application via the Image View instance before being written to the file system of the device and the corresponding URL stored in the photoURL variable for later reference Clearly the code expects the image file writing to be performed by a method named saveImageToFile which must now be implemented func saveImageToFile image UIImage NSURL let filemgr NSFileManager defaultManager let dirPaths filemgr URLsForDirectory DocumentDirectory inDomains UserDomainMask let filePath dirPaths 0 URLByAppendingPathComponent currentImage png path UIImageJPEGRepresentation image 0 5 writeToFile filePath atomically true return NSURL fileURLWithPath filePath The method obtains a reference to the application s Documents directory and constructs a path to an image file named currentImage png The image is then written to the file in JPEG format using a compression rate of 0 5 in order to reduce the amount of storage used from the application s iCloud allowance The resulting file URL is then returned to the calling method Saving a Record to the Cloud Database When the user has entered an address and comments and selected a photo the data is ready to be saved to the cloud database This will require that code be added to the saveRecord method as follows IBAction func saveRecord sender AnyObject if photoURL nil notifyUser No Photo message Use the Photo option to choose a photo for the record return let asset CKAsset fileURL photoURL let myRecord CKRecord recordType Houses myRecord setObject addressField text forKey address myRecord setObject commentsField text forKey comment myRecord setObject asset forKey photo publicDatabase saveRecord myRecord completionHandler returnRecord error in if let err error self notifyUser Save Error message err localizedDescription else dispatch async dispatch get main queue self notifyUser Success message Record saved successfully self currentRecord myRecord The method begins by verifying that the user has selected a photo to include in the database record If one has not yet been selected the user is notified that a photo is required the notifyUser method will be implemented in the next section Next a new CKAsset object is created and initialized with the URL to the photo image previously selected by the user A new CKRecord instance is then created and assigned a record type of Houses The record is then initialized with the content of the Text Field and Text View and the CKAsset object containing the photo image Finally the saveRecord method of the public cloud database is called passing through the newly created record A completion handler then reports the success or otherwise of the save operation Since this involves working with the user interface it is dispatched to the main thread to prevent the application from locking up The new record is then saved to the currentRecord variable where it can be referenced should the user subsequently decide to update or delete the record Implementing the notifyUser Method The notifyUser method takes as parameters two string values representing a title and message to be displayed to the user These strings are then used in the construction of an Alert View Implement this method as follows func notifyUser title String message String Void let alert UIAlertController title title message message preferredStyle UIAlertControllerStyle Alert let cancelAction UIAlertAction title OK style Cancel handler nil alert addAction cancelAction self presentViewController alert animated true completion nil Testing the Record Saving Method Compile and run the application on a device or simulator on which an iCloud account has been configured Enter text into the address and comments fields and select an image from the photo library images can be added to the photo library of a simulator instance by dragging images from a Finder window and dropping them onto the simulator window Tap the Save button to save the record and wait for the alert to appear indicating that the record has been saved successfully Note that CloudKit operations are performed asynchronously so the amount of time for a successful save to be reported will vary depending on the size of the record being saved network speed and responsiveness of the iCloud servers Once the record has been saved return to the Capabilities screen for the application Figure 50 1 and click on the CloudKit Dashboard button This will launch the default web browser on the system and load the CloudKit Dashboard portal Enter your Apple developer login and password and once the dashboard has loaded select the CloudKitDemo application from the drop down menu marked as A in Figure 50 3 From

    Original URL path: http://www.techotopia.com/index.php/An_iOS_9_CloudKit_Example (2016-02-13)
    Open archived version from archive

  • An iOS 9 CloudKit Subscription Example - Techotopia
    is committed to the cloud database using the saveSubscription method of the cloud database object For the purposes of this example the code to implement the subscription should be implemented in the viewDidLoad method located in the ViewController swift file eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters override func viewDidLoad super viewDidLoad publicDatabase container publicCloudDatabase let predicate NSPredicate format TRUEPREDICATE let subscription CKSubscription recordType Houses predicate predicate options FiresOnRecordCreation let notificationInfo CKNotificationInfo notificationInfo alertBody A new House was added notificationInfo shouldBadge true subscription notificationInfo notificationInfo publicDatabase saveSubscription subscription completionHandler returnRecord error in if let err error print subscription failed err localizedDescription else dispatch async dispatch get main queue self notifyUser Success message Subscription set up successfully Note that the NSPredicate object was created using TRUEPREDICATE This is a special value that configures the predicate to always return a true value and is the equivalent of indicating that all records of the specified type match the predicate The FiresOnRecordCreation option indicates that the user is to be notified whenever a new record of type Houses is added to the database Other options available are FiresOnRecordUpdate FiresOnRecordDelete and FiresOnce The FiresOnce option causes the subscription to be deleted from the server after it has fired for the first time Compile and run the application on a device or simulator then log into the iCloud Dashboard Display the settings for the CloudKitDemo application and select the Subscription Types entry in the left hand navigation panel If the subscription was successfully configured it should be listed as shown in Figure 51 1 Figure 51 1 Handling Remote Notifications When the user selects a notification alert on an iOS device the CloudKitDemo application will be launched by the operating system At the point that the user selects the notification the application will currently be in one of three possible states foreground background or not currently running If the application is in the background when the alert is selected it is simply brought to the foreground If it was not currently running the application is launched by the operating system and brought to the foreground When the application is already in foreground or background state when a CloudKit notification alert is selected the didReceiveRemoteNotification method of the application delegate class is called and passed as an argument an NSDictionary instance containing a CKNotification object which contains among other information the ID of the cloud database record that triggered the notification If the application was not already in the foreground or background when the alert is selected the didReceiveRemoteNotification method is not called Instead information about the database change is passed as an argument to the didFinishLaunchingWithOptions method of the application delegate Implementing the didReceiveRemoteNotification Method The didReceiveRemoteNotification method will be called when the user selects an alert and the CloudKitDemo application is either already in

    Original URL path: http://www.techotopia.com/index.php/An_iOS_9_CloudKit_Subscription_Example (2016-02-13)
    Open archived version from archive

  • An Overview of iOS 9 Multitouch, Taps and Gestures - Techotopia
    can be single taps or multiple taps and the event will contain information about the number of times a user tapped on the screen Touches A touch occurs when a finger establishes contact with the screen When more than one finger touches the screen each finger registers as a touch up to a maximum of five fingers Touch Notification Methods Touch screen events cause one of four methods on the first responder object to be called The method that gets called for a specific event will depend on the nature of the interaction In order to handle events therefore it is important to ensure that the appropriate methods from those outlined below are implemented within your responder chain These methods will be used in the worked example contained in the An Example iOS 9 Touch Multitouch and Tap Application and Detecting iOS 9 Touch Screen Gesture Motions chapters of this book touchesBegan method The touchesBegan method is called when the user first touches the screen Passed to this method are an argument called touches of type NSSet and the corresponding UIEvent object The touches object contains a UITouch event for each finger in contact with the screen The tapCount method of any of the UITouch events within the touches set can be called to identify the number of taps if any performed by the user Similarly the coordinates of an individual touch can be identified from the UITouch event either relative to the entire screen or within the local view itself touchesMoved method The touchesMoved method is called when one or more fingers move across the screen As fingers move across the screen this method gets called multiple times allowing the application to track the new coordinates and touch count at regular intervals As with the touchesBegan method this method is provided with an event object and an NSSet object containing UITouch events for each finger on the screen touchesEnded method This method is called when the user lifts one or more fingers from the screen As with the previous methods touchesEnded is provided with the event and NSSet objects touchesCancelled method When a gesture is interrupted due to a high level interrupt such as the phone detecting an incoming call the touchesCancelled method is called Touch Prediction A new feature introduced as part of the iOS 9 SDK is touch prediction Each time the system updates the current coordinates of a touch on the screen a set of algorithms attempt to predict the coordinates of the next location A finger sweeping across the screen for example will trigger multiple calls to the touchesMoved method passing through the current touch coordinates Also passed through to the method is a UIEvent object on which a method named predictedTouchesForTouch may be called passing through the touch object representing the current location In return the method will provide an array of UITouch objects that predict the next few locations of the touch motion This information can then be used to improve the performance

    Original URL path: http://www.techotopia.com/index.php/An_Overview_of_iOS_9_Multitouch,_Taps_and_Gestures (2016-02-13)
    Open archived version from archive



  •