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".
  • Managing Files using the iOS 7 UIDocument Class - Techotopia
    created outlet 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 saveDocument Implementing the Application Data Structure So far we have created and partially implemented a UIDocument subclass named MyDocument and designed the user interface of the application together with corresponding actions and outlets As previously discussed the MyDocument class will require two methods that are responsible for interfacing between the MyDocument object instances and the application s data structures Before we can implement these methods however we first need to implement the application data structure In the context of this application the data simply consists of the string entered by the user into the text view object Given the simplicity of this example we will declare the data structure such as it is within the MyDocument class where it can be easily accessed by the contentsForType and loadFromContents methods To implement the data structure albeit a single data value select the MyDocument h file and add a declaration for an NSString object import UIKit UIKit h interface MyDocument UIDocument property strong nonatomic NSString userText end Now that the data model is defined it is now time to complete the MyDocument class implementation Implementing the contentsForType Method The MyDocument class is a subclass of UIDocument When an instance of MyDocument is created and the appropriate method is called on that instance to save the application s data to a file the class makes a call to its contentsForType instance method It is the job of this method to collect the data to be stored in the document and to pass it back to the MyDocument object instance in the form of an NSData object The content of the NSData object will then be written to the document Whilst this may sound complicated most of the work is done for us by the parent UIDocument class All the method needs to do in fact is get the current value of the userText NSString object put it into an NSData object and return it Select the MyDocument m file and add the contentsForType method as follows id contentsForType NSString typeName error NSError autoreleasing outError return NSData dataWithBytes userText UTF8String length userText length Implementing the loadFromContents Method The loadFromContents instance method is called by an instance of MyDocument when the object is instructed to read the contents of a file This method is passed an NSData object containing the content of the document and is responsible for updating the application s internal data structure accordingly All this method needs to do therefore is convert the NSData object contents to a string and assign it to the userText object BOOL loadFromContents id contents ofType NSString typeName error NSError autoreleasing outError if contents length 0 userText NSString alloc initWithBytes contents bytes length contents length encoding NSUTF8StringEncoding else userText return YES The implementation of the MyDocument class is now complete and it is time to

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


  • Using iCloud Storage in an iOS 7 Application - Techotopia
    an observer to be notified when the search is finished The code to perform these tasks reads as follows metadataQuery NSMetadataQuery alloc init metadataQuery setPredicate NSPredicate predicateWithFormat K like document doc NSMetadataItemFSNameKey metadataQuery setSearchScopes NSArray arrayWithObjects NSMetadataQueryUbiquitousDocumentsScope nil NSNotificationCenter defaultCenter addObserver self selector selector metadataQueryDidFinishGathering name NSMetadataQueryDidFinishGatheringNotification object metadataQuery metadataQuery startQuery Once the metadataQuery startQuery method is called the search will run and trigger the metadataQueryDidFinishGathering method once the search is complete The next step therefore is to implement the metadataQueryDidFinishGathering method Before doing so however note that the viewDidLoad method is now complete and the full implementation should read as follows void viewDidLoad super viewDidLoad NSArray dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES NSString docsDir dirPaths 0 NSString dataFile docsDir stringByAppendingPathComponent document doc documentURL NSURL fileURLWithPath dataFile NSFileManager filemgr NSFileManager defaultManager filemgr removeItemAtURL documentURL error nil ubiquityURL filemgr URLForUbiquityContainerIdentifier nil URLByAppendingPathComponent Documents if filemgr fileExistsAtPath ubiquityURL path NO filemgr createDirectoryAtURL ubiquityURL withIntermediateDirectories YES attributes nil error nil ubiquityURL ubiquityURL URLByAppendingPathComponent document doc Search for document in iCloud storage metadataQuery NSMetadataQuery alloc init metadataQuery setPredicate NSPredicate predicateWithFormat K like document doc NSMetadataItemFSNameKey metadataQuery setSearchScopes NSArray arrayWithObjects NSMetadataQueryUbiquitousDocumentsScope nil NSNotificationCenter defaultCenter addObserver self selector selector metadataQueryDidFinishGathering name NSMetadataQueryDidFinishGatheringNotification object metadataQuery metadataQuery startQuery 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 Implementing the metadataQueryDidFinishGathering Method When the meta data query was triggered in the viewDidLoad method to search for documents in the application s iCloud storage area an observer was configured to call a method named metadataQueryDidFinishGathering when the initial search completed The next logical step is to implement this method The first task of the method is to identify the query object that caused this method to be called This object must then be used to disable any further query updates at this stage the document either exists or doesn t exist so there is nothing to be gained by receiving additional updates and stop the search It is also necessary to remove the observer that triggered the method call Combined these requirements result in the following code NSMetadataQuery query notification object query disableUpdates NSNotificationCenter defaultCenter removeObserver self name NSMetadataQueryDidFinishGatheringNotification object query query stopQuery Next the query method of the query object needs to be called to extract an array of documents located during the search NSArray results NSArray alloc initWithArray query results A more complex application would in all likelihood need to implement a for loop to iterate through more than one document in the array Given that the iCloudStore application searched for only one specific file name we can simply check the array element count and assume that if the count is 1 then the document already exists In this case the ubiquitous URL of the document from the query object needs to be assigned to our ubiquityURL member property and used to create an instance of our MyDocument

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

  • Synchronizing iOS 7 Key-Value Data using iCloud - Techotopia
    Resolution In the event that two application instances make changes 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 NSUbiquitousKeyValue StoreDidChangeExternallyNotification 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 for either the iPad or iPhone with the name and class prefix of iCloudKeys 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 Use key value store option Figure 37 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

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

  • IOS 7 Data Persistence using Archiving - Techotopia
    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 UILabels three UITextFields and a single UIButton 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 38 1 Figure 38 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 ArchiveViewController h file Ctrl click on the text field object again and drag to a position just below the interface 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 newly created outlets 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 Select the ArchiveViewController h file and add an additional NSString property to store a reference to the path to the archive data file import UIKit UIKit h interface ArchiveViewController UIViewController property strong nonatomic IBOutlet UITextField name property strong nonatomic IBOutlet UITextField address property strong nonatomic IBOutlet UITextField phone property strong nonatomic NSString dataFilePath IBAction saveData end 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 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 ArchiveViewController m 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 void viewDidLoad super viewDidLoad NSFileManager filemgr NSString docsDir NSArray dirPaths filemgr NSFileManager defaultManager Get the documents directory dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES

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

  • IOS 7 Database Implementation using SQLite - Techotopia
    Applications id Documents Where user is the login name of the user running the iOS Simulator session sdk version is the version of the iOS SDK used to build the application 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 Firstly 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 Figure 39 1 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 Secondly the sqlite3 h include file must be imported into any files where references are made to SQLite definitions declarations or functions This file may be imported when needed as follows import sqlite3 h Key SQLite Functions When implementing a database using SQLite it will be necessary to utilize a number of C functions contained within the libsqlite3 dylib library A summary of the most commonly used functions is as follows sqlite3 open Opens specified database file If the database file does not already exist it is created sqlite3 close Closes a previously opened database file sqlite3 prepare v2 Prepares a SQL statement ready for execution sqlite3 step Executes a SQL statement previously prepared by the sqlite3 prepare v2 function sqlite3 column type Returns a data field from the results of a SQL retrieval operation where type is replaced by the data type of the data to be extracted text blob bytes int int16 etc sqlite3 finalize Deletes a previously prepared SQL statement from memory sqlite3 exec Combines the functionality of sqlite3 prepare v2 sqlite3 step and sqlite3 finalize into a single function call This of course represents only a small subset of the complete range of functions available with SQLite A full list can be found at http www sqlite org c3ref funclist html Declaring a SQLite Database Before any tasks can be performed on a database it must first be declared To do so it is necessary to declare a variable that points to an instance of a structure of type sqlite3 the sqlite3 structure is defined in the sqlite3 h include file For example sqlite3 contactDB Declare a pointer to sqlite database structure 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

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

  • An Example SQLite based iOS 7 Application - Techotopia
    address phone and status respectively Ctrl click on the Save button object and drag the line to the area immediately beneath the newly created outlet 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 On completion of these steps the DatabaseViewController h file should read as follows import UIKit UIKit h import sqlite3 h interface DatabaseViewController UIViewController property strong nonatomic IBOutlet UITextField name property strong nonatomic IBOutlet UITextField address property strong nonatomic IBOutlet UITextField phone property strong nonatomic IBOutlet UILabel status IBAction saveData id sender IBAction findContact id sender property strong nonatomic NSString databasePath property nonatomic sqlite3 contactDB end 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 DatabaseViewController m file scroll down to the viewDidLoad method and modify it as follows void viewDidLoad super viewDidLoad NSString docsDir NSArray dirPaths Get the documents directory dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES docsDir dirPaths 0 Build the path to the database file databasePath NSString alloc initWithString docsDir stringByAppendingPathComponent contacts db NSFileManager filemgr NSFileManager defaultManager if filemgr fileExistsAtPath databasePath NO const char dbpath databasePath UTF8String if sqlite3 open dbpath contactDB SQLITE OK char errMsg const char sql stmt CREATE TABLE IF NOT EXISTS CONTACTS ID INTEGER PRIMARY KEY AUTOINCREMENT NAME TEXT ADDRESS TEXT PHONE TEXT if sqlite3 exec contactDB sql stmt NULL NULL errMsg SQLITE OK status text Failed to create table sqlite3 close contactDB else status text Failed to open create database 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 Creates an NSFileManager instance and subsequently uses it to detect if the database file already exists If the file does not yet exist the code converts the path to a UTF 8 string and creates the database via a call to the SQLite sqlite3 open function passing through a reference to the contactDB variable declared previously in the interface file Prepares a SQL statement to create the contacts table in the database Reports the success or otherwise of the operation via the status label Closes the database 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 Implementing the Code to Save Data to the SQLite Database The saving of contact data to the database is the responsibility of

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

  • Working with iOS 7 Databases using Core Data - Techotopia
    data object as though a relationship had been defined between those entities Fetched properties lack the flexibility of relationships and are referred to by Apple s Core Data documentation as weak one way relationships best suited to loosely coupled relationships Fetch request A predefined query that can be referenced to retrieve data objects based on defined predicates For example a fetch request can be configured into an entity to retrieve all contact objects where the name field matches John Smith Persistent Store Coordinator The persistent store coordinator is responsible for coordinating access to multiple persistent object stores As an iOS developer you will never directly interact with 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 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 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 41 2 Figure 41 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

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

  • An iOS 7 Core Data Tutorial - Techotopia
    View Controller With a storyboard file added and configured into the application we now need to create a view controller Within the Xcode project navigator panel Ctrl click on the CoreData folder entry From the popup menu select New File In the new file panel select the iOS Cocoa Touch category followed by the Objective C class icon and click Next On the following options screen make sure the Subclass of menu is set to UIViewController and name the class CoreDataViewController Also make sure the Targeted for iPad and With XIB for user interface options are off Click Next and select a location for the new class files before clicking on Create All that remains in this phase of the tutorial is to add a UIViewController instance to the storyboard and to associate it with our newly created view controller class Select the Main storyboard file and drag and drop a View Controller instance from the Object Library panel onto the storyboard design canvas Select this new view controller so that it is highlighted in blue display the Identity Inspector panel and change the Class setting from UIViewController to our new CoreDataViewController class The new storyboard file and view controller are now ready Designing the User Interface With the storyboard and view controller configured 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 42 4 note that objects may be cut and pasted from the previous Database project to save time in designing the user interface layout Figure 42 4 Before proceeding stretch the status label located above the two buttons so that it covers most of the width of the view 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 CoreDataViewController h file Ctrl click on the text field object again and drag to a position just below the interface 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 newly created outlet 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 With the connections established select

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



  •