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".
  • Synchronizing iOS 8 Key-Value Data using iCloud - Techotopia
    to the same key value pair the most recent change is given precedence Receiving Notification of Key Value Changes An application may register to be notified when stored values are changed by another application instance This is achieved by setting up an observer on the NSUbiquitousKeyValueStoreDidChangeExternallyNotification notification This notification is triggered when a change is made to any key value pair in a specified key value store and is passed an array of strings containing the keys that were changed together with an NSNumber indicating the reason for the change In the event that the available space for the key value storage has been exceeded this number will match the NSUbiquitousKeyValueStoreQuotaViolationChange constant value An iCloud Key Value Data Storage Example The remainder of this chapter is devoted to the creation of an application that uses iCloud key value storage to store a key with a string value using iCloud In addition to storing a key value pair the application will also configure an observer to receive notification when the value is changed by another application instance Begin the application creation process by launching Xcode and creating a new Single View Application project named iCloudKeys with the device menu set to Universal and Swift selected as the programming language Enabling the Application for iCloud Key Value Data Storage A mandatory step in the development of the application is to configure the appropriate iCloud entitlement This is achieved by selecting the application target at the top of the Xcode project navigator panel and selecting the Capabilities tab in the main project settings panel Switch on iCloud support and enable the Key value storage option Figure 39 1 Once selected Xcode will create an entitlements file for the project named iCloudKeys entitlements containing the appropriate iCloud entitlements key value pairs Select the entitlements file from the project navigator and note the value assigned to the ubiquity kvstore identity key By default this is typically comprised of your team or individual developer ID combined with the application s Bundle identifier Any other applications that use the same value for the entitlement key will share access to the same iCloud based key value data stored by this application eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 The application is going to consist of a text field into which a string may be entered by the user and a button which when selected will save the string to the application s iCloud key value data store Select the Main storyboard file display the object library View Utilities Show Object Library and drag and drop the two objects into the view canvas Double click on the button object and change the text to Store Key The completed view should resemble Figure 39 2 Figure 39 2 Click on the background View

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


  • IOS 8 Data Persistence using Archiving and Swift - Techotopia
    data is unarchived and used to recreate the array object The restored data is then extracted from the array object and presented to the user Begin by launching Xcode and create a new project named Archive using the Single View Application template Select Universal from the device menu and choose Swift as the programming language Once the main Xcode project window appears populated with the template files it is time to start developing the application Designing the User Interface The user interface for our application is going to consist of three Labels three TextFields and a single Button Select Main storyboard in the Xcode project navigator and display the Object Library panel View Utilities Show Object Library if it is not already visible Drag drop resize position and configure objects on the View window canvas until your design approximates that illustrated in Figure 40 1 Figure 40 1 The next step is to establish the connections to our action and outlets 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 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 to properties named address and phone respectively Ctrl click on the 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 saveData Close the Assistant Editor select the ViewController swift file and add an additional variable to store a reference to the path to the archive data file import UIKit class ViewController UIViewController IBOutlet weak var name UITextField IBOutlet weak var address UITextField IBOutlet weak var phone UITextField var dataFilePath String Checking for the Existence of the Archive File on Startup Each time the application is launched by the user the code will need to identify whether the archive data file exists from a previous session In the event that it does exist the application will need to read the contents to recreate the original array object from which the archive was created Using this newly recreated array object the array elements will then be extracted and used to populate the name address and phone text fields The traditional location for placing such initialization code is in the viewDidLoad method of the view controller class Within the project window therefore select the ViewController swift file and scroll down the contents of this file until you reach the viewDidLoad method Having located the method modify it as outlined in the following code fragment override func viewDidLoad super viewDidLoad let filemgr NSFileManager defaultManager let dirPaths NSSearchPathForDirectoriesInDomains DocumentDirectory

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

  • Swift iOS 8 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 dylib 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 dylib 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/Swift_iOS_8_Database_Implementation_using_SQLite (2016-02-13)
    Open archived version from archive

  • An Example SQLite based iOS 8 Application using Swift and FMDB - Techotopia
    42 4 Figure 42 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 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 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 NSSearchPathForDirectoriesInDomains DocumentDirectory UserDomainMask true let docsDir dirPaths 0 as String databasePath docsDir stringByAppendingPathComponent contacts db if filemgr fileExistsAtPath databasePath as String let contactDB FMDatabase path databasePath as String if contactDB nil println 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 println Error contactDB lastErrorMessage contactDB close else println Error contactDB lastErrorMessage The code in the above method performs the following tasks Identifies the

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

  • IOS 8 Databases in Swift using Core Data - Techotopia
    the persistence store coordinator and in fact will very rarely need to develop an application that requires more 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 43 2 Figure 43 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 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 43 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 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 Obtaining the Managed Object Context Since many of the Core Data methods require the managed

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

  • An iOS 8 Swift Core Data Tutorial - Techotopia
    of the entity class name By default the new entity has been assigned a class name of Contacts This needs to be changed to CoreDataDemo Contacts reflecting the namespace given to the application when it was first created in Xcode To make this change load the CoreDataDemo xcdmodeld file into the entity editor select the Contacts entity name from the left hand panel and display the Data Model Inspector in the Utilities panel as illustrated in Figure 44 5 Figure 44 5 Within the Class field change the name to CoreDataDemo Contacts eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 44 6 note that objects may be cut and pasted from the previous Database project to save time in designing the user interface layout Figure 44 6 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 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

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

  • An Introduction to CloudKit Data Storage on iOS 8 - 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 8 CloudKit Example The overall concept of an application cloud container private and public databases and records can be visualized as illustrated in Figure 45 1 Figure 45 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_8 (2016-02-13)
    Open archived version from archive

  • An iOS 8 CloudKit Example - Techotopia
    the background view of the user interface override func touchesBegan touches Set NSObject 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 stub 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 NSString 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 NSObject 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 dirPaths NSSearchPathForDirectoriesInDomains DocumentDirectory UserDomainMask true let docsDir AnyObject dirPaths 0 let filePath docsDir stringByAppendingPathComponent currentImage png 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 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 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 46 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

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