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".
  • Using iCloud Storage in an iOS 5 iPhone Application - Techotopia
    URLForUbiquityContainerIdentifier method of the NSFileManager passing through the UBIQUITY CONTAINER URL constant as an argument Since it is recommended that documents be stored in the Documents sub directory this needs to be appended to the URL path ubiquityURL filemgr URLForUbiquityContainerIdentifier UBIQUITY CONTAINER URL URLByAppendingPathComponent Documents By default the iCloud storage area for the application will not already contain a Documents sub directory so the next step is to check to see if the sub directory already exists and in the event that is does not create it if filemgr fileExistsAtPath ubiquityURL path NO filemgr createDirectoryAtURL ubiquityURL withIntermediateDirectories YES attributes nil error nil Having created the Documents directory if necessary the next step is to append the document name document doc to the end of the ubuiquityURL path ubiquityURL ubiquityURL URLByAppendingPathComponent document doc The final task for the viewDidLoad method is to initiate a search in the application s iCloud storage area to find out if the document doc file already exists and to act accordingly subject to the result of the search The search is performed by calling the methods on an instance of the NSMetaDataQuery object This involves creating the object setting a predicate to indicate the files to search for and defining a ubiquitous search scope in other words instructing the object to search iCloud storage Once initiated the search is performed on a separate thread and issues a notification when completed For this reason it is also necessary to configure 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 objectAtIndex 0 NSString dataFile docsDir stringByAppendingPathComponent document doc self documentURL NSURL fileURLWithPath dataFile NSFileManager filemgr NSFileManager defaultManager filemgr removeItemAtURL documentURL error nil ubiquityURL filemgr URLForUbiquityContainerIdentifier UBIQUITY CONTAINER URL 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 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

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


  • Synchronizing iPhone iOS 5 Key-Value Data using iCloud - Techotopia
    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 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 Summary tab in the main panel Scroll down the summary information until the entitlements section comes into view and turn on the Enable Entitlements option Figure 29 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 your reverse company domain URL and application ID 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 Implementing the View Controller 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 As such the application will need an outlet to the text field and method to be called when the button is selected In addition an instance of the NSUbiquitousKeyStore class will be needed Choose the iCloudKeysViewController h file therefore and modify it as follows import UIKit UIKit h interface iCloudKeysViewController UIViewController UITextField textField NSUbiquitousKeyValueStore keyStore property strong nonatomic IBOutlet UITextField textField IBAction saveKey end Modifying the viewDidLoad Method Having declared the outlets and action for the user interface and created a variable to point to the NSUbiquitousKeyValueStore object the next step is to modify the viewDidLoad method of the view controller Select the iCloudKeysViewController m implementation file and modify it to add the

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

  • IOS 5 iPhone Data Persistence using Archiving - Techotopia
    reads as follows import UIKit UIKit h interface archiveViewController UIViewController UITextField name UITextField address UITextField phone NSString dataFilePath 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 Having made the appropriate declarations in the interface file the next step is to move to the archiveViewController m implementation file where we will synthesize the access methods for our instance variables and create a template method for the saveData action method import archiveViewController h implementation archiveViewController synthesize name address phone dataFilePath void saveData end Next make sure that we free up memory that we have allocated when the application exists Memory Management Having allocated memory in implementing the above outlets it is important that we add code to indicate that resources can be freed when the view is no longer needed To do so edit the archiveViewController m file again and modify the viewDidUnload method as follows void viewDidUnload Release any retained subviews of the main view e g self myOutlet nil self name nil self address nil self phone nil self dataFilePath nil We will need to do some more coding later but at this point it makes sense to design the user interface and establish the connections between the user interface object and the outlets and action we have declared so far Designing the User Interface The user interface for our application is going to consist of three UILabels three UITextFields and single UIButton Select archiveViewController xib in the main 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 30 1 Figure 30 1 The next step is to establish the connections to our action and outlets Beginning with the outlets hold down the Ctrl key and click and drag from the File s Owner object to the text field component located to right of the Name label object Release the Ctrl key and mouse button and select the name outlet from the resulting menu Repeat these steps for the address and phone text fields connecting them to the corresponding outlets To connect the action select the Save button object in the view window and display the Connections Inspector View Utilities Show Connections Inspector Click with the mouse within the small round circle to the right of the Touch Up Inside event and drag the blue line to the File s Owner object Release the mouse button and select the saveData method from the resulting menu 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 archive will need to read the contents to recreate the original array object

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

  • IOS 5 iPhone Database Implementation using SQLite - Techotopia
    on the host system in the following folder Users user Library Application Support iPhone Simulator sdk version 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 iPhone 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 31 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 is located in the usr include directory and may be imported when needed as follows import usr include 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 Opening or Creating a Database

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

  • An Example SQLite based iOS 5 iPhone Application - Techotopia
    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 objectAtIndex 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 Implementing the Code to Save Data to the SQLite Database The saving of contact data to the database is the responsibility of the saveData action method This method will need to open the database file extract the text from the three text fields and construct and execute a SQL INSERT statement to add this data as a record to the database Having done this the method will then need to close the database In addition the code will need to clear the text fields ready for the next contact to be entered and update the status label to reflect the success or failure of the operation In order to implement this behavior therefore we need to modify the template method created previously as follows void saveData sqlite3 stmt statement const char dbpath databasePath UTF8String if sqlite3 open dbpath contactDB SQLITE OK NSString insertSQL NSString stringWithFormat INSERT INTO CONTACTS name address phone VALUES name text address text phone text const char insert stmt insertSQL UTF8String sqlite3 prepare v2 contactDB insert stmt 1 statement NULL if sqlite3 step statement SQLITE DONE status text Contact added name text address text phone text else status text Failed to add contact sqlite3 finalize statement sqlite3 close contactDB The next step in our application development process

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

  • Working with iOS 5 iPhone Databases using Core Data - Techotopia
    one one to many or many to many Fetched property This provides an alternative to defining relationships Fetched properties allow properties of one data object to be accessed from another 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 iPhone 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 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 33 2 Figure 33 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 where a name may be typed To add attributes to the entity click on the Add Attribute button located in the bottom panel 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

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

  • An iOS 5 iPhone Core Data Tutorial - Techotopia
    m implementation file to initialize and allocate the coreDataViewController instance and assign it as the window view so that it is visible to the user Note also that we have to import coreDataViewController h into this file and synthesize accessors for the viewController object import coreDataAppDelegate h import coreDataViewController h implementation coreDataAppDelegate synthesize window window synthesize managedObjectContext managedObjectContext synthesize managedObjectModel managedObjectModel synthesize persistentStoreCoordinator persistentStoreCoordinator synthesize viewController BOOL application UIApplication application didFinishLaunchingWithOptions NSDictionary launchOptions self window UIWindow alloc initWithFrame UIScreen mainScreen bounds Override point for customization after application launch viewController coreDataViewController alloc initWithNibName coreDataViewController bundle nil self window backgroundColor UIColor whiteColor self window addSubview viewController view self window makeKeyAndVisible return YES end Adding Actions and Outlets to the View Controller As with previous instances of our Contacts application our Core Data example will include a user interface that needs to accept and display name address and phone information and to react to the selection of the save and find buttons In addition a status label will be used to provide the user with feedback To declare the outlets and actions associated with these user interface components select the coreDataViewController h file and modify the class declaration so that it reads as follows import UIKit UIKit h interface coreDataViewController UIViewController UITextField name UITextField address UITextField phone UILabel status 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 IBAction findContact end Next select the coreDataViewController m implementation file add an synthesize directive for the outlets import the coreDataAppDelegate h file and add template methods for the two declared actions import coreDataViewController h import coreDataAppDelegate h implementation coreDataViewController synthesize name address phone status void saveData void findContact end Designing the User Interface With the actions and outlets defined now is a good time to design the user interface and establish the connections so select the coreDataViewController xib 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 34 3 Figure 34 3 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 Next connect the three text fields and status label to the name address phone and status outlets respectively by holding down the Ctrl key and clicking and dragging from File s Owner icon to the corresponding component From the resulting menu select the outlet corresponding to the selected view object The last step involves connecting the two buttons to the corresponding actions First display the Connections Inspector View Utilities Show Connections Inspector then select the Save button Click inside the small circle next to the Touch Up Inside event in the Connections Inspector panel and drag the blue line to the File

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

  • An Overview of iOS 5 iPhone Multitouch, Taps and Gestures - Techotopia
    response chain defined by the object s nextResponder property for further processing and so on up the chain If the first responder is not able to handle the event it will also pass it to the next responder in the chain and so on until it either reaches a responder that handles the event or it reaches the end of the chain the UIApplication object where it will either be handled or discarded Take for example a UIView with a UIButton subview If the user touches the screen over the button then the button as first responder will receive the event If the button is unable to handle the event it will need to be passed up to the view object If the view is also unable to handle the event it would then be passed to the view controller and so on When working with the responder chain it is important to note that the passing of an event from one responder to the next responder in the chain does not happen automatically If an event needs to be passed to the next responder code must be written to make it happen Forwarding an Event to the Next Responder An event may be passed on to the next responder in the response chain by calling the nextResponder method of the current responder passing through the method that was triggered by the event and the event itself Take for example a situation where the current responder object is unable to handle a touchesBegan event In order to pass this to the next responder the touchesBegan method of the current responder will need to make a call as follows void touchesBegan NSSet touches withEvent UIEvent event self nextResponder touchesBegan touches withEvent event Gestures Gesture is an umbrella term used to encapsulate any single interaction between the touch screen and the user starting at the point that the screen is touched by one or more fingers and the time that the last finger leaves the surface of the screen Swipes pinches stretches and flicks are all forms of gesture Taps A tap as the name suggests occurs when the user touches the screen with a single finger and then immediately lifts it from the screen Taps 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

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



  •