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 the UIPickerView and UIDatePicker Components in iOS 5 iPad Applications - Techotopia
    row as being selected in the far left hand component The UIDatePicker component is a pre configured class designed specifically for the selection of dates and times The UIPickerView class on the other hand allows for the creation of custom picker controls and will explored in An iOS 5 iPad UIPickerView Example A DatePicker Example By way of introduction to the concept of using pickers in an iOS 5 iPad application we will begin with a very simple example that utilizes the UIDatePicker class The application will consist of a DatePicker a label and a button When the button is pressed by the user the date and time selected in the picker will be displayed on the label component Begin by creating a new iOS iPad project using the Single View Application template without Storyboard support and enter datePicker for both the product name and class prefix Once the main Xcode project window appears select the datePickerViewController h file modify it to add the outlets for the user interface objects and add a declaration for the action method to be called when the user touches the button import UIKit UIKit h interface datePickerViewController UIViewController property strong nonatomic IBOutlet UIDatePicker datePicker property strong nonatomic IBOutlet UILabel dateLabel IBAction getSelection end Designing the User Interface Select the datePickerViewController xib file and drag and drop the Date Picker Label and Button components from the Object Library panel View Utilities Show Object Library onto the view and modify and position the layout so that the view resembles Figure 27 2 Figure 27 2 Note that the text of the label is centered and that it has been stretched to be wider than the default size The configuration of the Date Picker object such as date format etc may be changed if desired via a variety of properties accessed by selecting the object in the view and displaying the Attributes Inspector View Utilities Show Attribute Inspector Establish connections between the outlet defined in the datePickerViewController h file and the Date Picker by Ctrl clicking on the File s Owner icon and dragging the resulting line to the Date Picker object in the view window Release the pointer and select datePicker from the resulting menu Repeat this task to connect the dateLabel outlet to the Label object Finally select the button in the view window and display the Connections Inspector View Utilities Show Connections Inspector Click in the circle to the right of the Touch Up Inside event and drag the line to the File s Owner entry From the resulting menu select the getSelection action method Coding the Date Picker Example Functionality Now that the outlets and user interface have been implemented it is time to write the functional code that will make the application work In actual fact the only method that needs to be implemented for this simple example is the getSelection action method that is called when the user touches the button In addition the synthesize directive for the two outlets also

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


  • An iOS 5 iPad UIPickerView Example - Techotopia
    PickerView instance is the best place to implement these two protocols The pickerViewController h File The first step is to implement the declarations in the pickerViewController h file Since we plan on making our view controller both the delegate and data source for the UIPickerView instance the view controller must be declared as implementing both the UIPickerViewDelegate and UIPickerViewDataSource protocols Our application also needs outlets to the UIPickerView and the two label objects that will be placed into the user interface In addition two arrays are needed to store the values for the product model and memory configurations respectively import UIKit UIKit h interface pickerViewController UIViewController UIPickerViewDelegate UIPickerViewDataSource property nonatomic strong IBOutlet UIPickerView modelPicker property nonatomic strong NSArray modelArray property nonatomic strong NSArray memoryArray property nonatomic strong IBOutlet UILabel modelLabel property nonatomic strong IBOutlet UILabel memoryLabel end Designing the User Interface Select the pickerViewController xib file to load it into Interface Builder Drag and drop a UIPickerView from the Object library View Utilities Object Library onto the view and position it at the top of the view Also add two labels and position them beneath the PickerView object Stretch the right and left hand edges of the labels until the dotted blue margin line appears Using the Attribute Inspector View Utilities Attribute Inspector configure centered alignment on the labels and increase the font size to 24pt Once completed the view should appear as illustrated in the following figure Figure 28 1 Next Ctrl click on the File s Owner icon and drag the resulting line to the PickerView component in the view After releasing the line select the modelPicker outlet from the menu Repeat these steps to connect the modelLabel and memoryLabel outlets to the label objects Next select the PickerView component in the View window and display the Connections Inspector View Utilities Connections Inspector Click in the round circle to the right of the dataSource outlet in the inspector window and drag the line to the File s Owner object Repeat this task for the delegate outlet The user interface is now designed and the outlets connected Initializing the Arrays The data that will be used in our application is stored in two arrays one for the iPad model and the other for the corresponding memory configuration These arrays need to be initialized when the application loads so the necessary code should be added to the viewDidLoad method of the pickerViewController m file Now is also a good time to add the appropriate synthesize directives import pickerViewController h interface pickerViewController end implementation pickerViewController synthesize modelPicker memoryArray modelArray synthesize memoryLabel modelLabel void viewDidLoad super viewDidLoad self modelArray NSArray alloc initWithObjects iPad WiFi iPad WiFi 3G AT T iPad WiFi 3G Verizon nil self memoryArray NSArray alloc initWithObjects 16GB 32GB 64GB nil end Implementing the DataSource Protocol The next step is to implement the methods that comprise the UIPickerViewDataSource protocol Since we have declared the pickerViewController class as the data source we need to implement the methods in the pickerViewController m

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

  • Working with Directories on iOS 5 - Techotopia
    by a character The current working directory may be identified at any time through a call to the currentDirectoryPath method of the file manager object For example the following code fragment identifies the current working directory NSFileManager filemgr NSString currentPath filemgr NSFileManager defaultManager currentPath filemgr currentDirectoryPath In this code we declare a new object named filemgr that is an instance of the NSFileManager class and also an NSString object named currentPath to contain the current working directory path Having obtained a file manager reference we then call the currentDirectoryPath method of that instance and assign the resulting string to currentPath Identifying the Documents Directory As previously discussed each iPad iOS application on a device has its own private Documents and tmp directories into which it is permitted to read and write data Because the location of these directories is different for each application the only way to find the correct path is to ask iOS In fact the exact location will also differ depending on whether the application is running on a physical iPad device or in the iOS Simulator The Documents directory for an application may be identified by making a call to a C function named NSSearchPathForDirectoriesInDomains passing through an argument in this case NSDocumentDirectory indicating that we require the path to the Documents directory Since this is a C function as opposed to a method of an Objective C class there is no need for us to establish an instance of a Foundation class such as NSFileManager before making the call That said the function does return an object in the form of an NSArray containing the results of the request We can therefore obtain the path to the current application s Documents directory as follows NSArray dirPaths NSString docsDir dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES docsDir dirPaths objectAtIndex 0 When executed the above code will assign the path to the Documents directory to the docsDir string When executed within the iOS Simulator environment the path returned will take the form of Users user name Library Application Support iPhone Simulator sdk version Applications app id Documents Where user name is the name of the user currently logged into the Mac OS X system on which the simulator is running sdk version is the version of the iOS SDK used to compile the application and app id is the unique ID of the app for example 06A3AEBA 8C34 476E 937F A27BDD2E450A Clearly this references a path on your Mac OS X system so feel free to open up a Finder window and explore the file system sandbox areas for your iOS iPad applications When executed on a physical iPad device the path returned by the function call will take the following form var mobile Applications app id Documents Identifying the Temporary Directory In addition to the Documents directory iOS iPad applications are also provided with a tmp directory for the storage of temporary files The path to the current application s temporary directory may be ascertained with a call

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

  • Working with iPad Files on iOS 5 - Techotopia
    and an optional NSError object The success of the operation is as usual reported in the form of a boolean YES or NO return value NSFileManager filemgr filemgr NSFileManager defaultManager if filemgr removeItemAtPath tmp myfile txt error NULL YES NSLog Remove successful else NSLog Remove failed Creating a Symbolic Link A symbolic link to a particular file may be created using the createSymbolicLinkAtPath method This takes as arguments the path of the symbolic link the path to the file to which the link is to refer and an optional NSError object For example the following code creates a symbolic link from Users demo file1 txt that links to the pre existing file tmp myfile txt NSFileManager filemgr filemgr NSFileManager defaultManager if filemgr createSymbolicLinkAtPath Users demo file1 txt withDestinationPath tmp myfile txt error NULL YES NSLog Remove successful else NSLog Remove failed Reading and Writing Files with NSFileManager The NSFileManager class includes some basic file reading and writing capabilities These capabilities are somewhat limited when compared to the options provided by the NSFileHandle class but can be useful nonetheless Firstly the contents of a file may be read and stored in an NSData object through the use of the contentsAtPath method NSFileManager filemgr NSData databuffer filemgr NSFileManager defaultManager databuffer filemgr contentsAtPath tmp myfile txt Having stored the contents of a file in an NSData object that data may subsequently be written out to a new file using the createFileAtPath method databuffer filemgr contentsAtPath tmp myfile txt filemgr createFileAtPath tmp newfile txt contents databuffer attributes nil In the above example we have essentially copied the contents from an existing file to a new file This however gives us no control over how much data is to be read or written and does not allow us to append data to the end of an existing file If the file tmp newfile txt in the above example had already existed it and any data it contained would have been overwritten by the contents of the source file Clearly some more flexible mechanism is required This is provided by the Foundation Framework in the form of the NSFileHandle class Working with Files using the NSFileHandle Class The NSFileHandle class provides a range of methods designed to provide a more advanced mechanism for working with files In addition to files this class can also be used for working with devices and network sockets In the following sections we will look at some of the more common uses for this class Creating an NSFileHandle Object An NSFileHandle object can be created when opening a file for reading writing or updating in other words both reading and writing This is achieved using the fileHandleForReadingAtPath fileHandleForWritingAtPath and fileHandleForUpdatingAtPath methods respectively Having opened a file it must subsequently be closed when we have finished working with it using the closeFile method If an attempt to open a file fails for example because an attempt is made to open a non existent file for reading these methods return nil For example

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

  • IOS 5 iPad Directory Handling and File I/O – A Worked Example - Techotopia
    to the code later to add the required functionality but before doing so we need to design the user interface for our application Designing the User Interface As previously described our application is going to consist of a button and a text view To begin the user interface design process select the FileExampleViewController xib file to load it into the Interface Builder environment Drag a UIButton and then a UITextView from the Object library panel View Utilities Show Object Library onto the view Double click on the button and change the text to Save Position the components and resize the width of the text field so that the layout appears as illustrated Figure 32 1 Figure 32 1 The next step is to establish the connections between the user interface components and the action and outlet created in the view controller code Open the Connections Inspector panel View Utilities Show Connections Inspector and select the button object in the view window so that the available events for that object are listed Click in the small 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 saveText action method from the resulting menu to create the connection To connect the text field to the textBox outlet declared in the view controller interface file press and hold the control key click with the mouse over the File s Owner and drag the blue line to the text view object in the view window Release and select the textBox entry from the resulting menu Select the text view object display the Attributes Inspector and delete the sample Latin text Checking the Data File on Application Startup Each time the application is launched by the user it will need to check to see if the data file already exists if the user has not previously saved any text the file will not have been created If the file does exist the contents need to be read by the application and displayed within the text view A good place to put initialization code of this nature is in the viewDidLoad method of the view controller With this in mind select the FileExampleViewController m file scroll down to the viewDidLoad method and edit it as follows void viewDidLoad super viewDidLoad NSFileManager filemgr NSString dataFile NSString docsDir NSArray dirPaths filemgr NSFileManager defaultManager Identify the documents directory dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES docsDir dirPaths objectAtIndex 0 Build the path to the data file dataFile docsDir stringByAppendingPathComponent datafile dat Check if the file already exists if filemgr fileExistsAtPath dataFile Read file contents and display in textBox NSData databuffer databuffer filemgr contentsAtPath dataFile NSString datastring NSString alloc initWithData databuffer encoding NSASCIIStringEncoding textBox text datastring Before proceeding we need to take some time to talk about what the above code is doing First we declare some variables that will be used in the method and then create an instance of the NSFileManager class

    Original URL path: http://www.techotopia.com/index.php/IOS_5_iPad_Directory_Handling_and_File_I/O_%E2%80%93_A_Worked_Example (2016-02-13)
    Open archived version from archive

  • Preparing an iOS 5 App to use iCloud Storage - Techotopia
    leave the Bundle Seed menu set to Generate New and provide a bundle identifier formatted as follows com yourdomain yourappname In the above example com yourdomain will need to be replaced by the reverse URL of your domain name Click on Submit and note that the new app ID is now listed on the main App ID screen Figure 33 1 Note from the iCloud column of the table that this functionality is currently enabled This is the default setting In the event that iCloud support was not enabled by default or to disable the option click on Configure link to display the Configure App ID screen Select the check box next to Enable for iCloud and click Done to commit the configuration change Figure 33 2 Creating and Installing an iCloud Enabled Provisioning Profile Having creating an iCloud enabled App ID the next step is to incorporate that ID into a provisioning profile Remaining in the iOS Provisioning Portal click on the Provision link and in the resulting screen click on the New Profile button Within the Create New iOS Development Provisioning Profile screen name the new profile and select the development certificate to be used for the profile Using the App ID menu select the App ID created in the previous section followed by the devices on which the app is to be permitted to run before clicking on the Submit button If the new profile is listed as Pending in the main Provisioning screen simply use the browser reload button to refresh the page Once the profile is listed as active click on the Download button to save the mobileprovision file to your local system Once downloaded drag and drop the file onto the Xcode icon in the desktop dock to install it into the provisioning profiles library At this point the Xcode Organizer window should appear Connect your iPad to the system so that it is listed under DEVICES in the left hand panel of the Organizer window Select Provisioning Profiles from beneath the LIBRARY heading and drag and drop the new profile onto the Provisioning Profiles entry located beneath the iPad device under the DEVICES heading Once completed the provisioning profile is installed and ready to be used when developing an application Creating an iCloud Entitlements File Any applications that intend to use iCloud storage in any way must obtain entitlements appropriate to the iCloud features to be used These entitlements are placed into an entitlements file that is included in the Xcode project and built into the application at compile time If the application is intended to make use of iCloud document storage then the entitlements file must include a request for the com apple developer ubiquity container identifiers entitlement Similarly if the key value store is to be used then the com apple developer ubiquity kvstore identifier entitlement must be included Applications that require both forms of iCloud storage must include both entitlements The entitlements file is an XML file in which the

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

  • Managing Files using the iOS 5 UIDocument Class - Techotopia
    created the next step is to begin implementing the user interface and the corresponding outlets and actions Declaring the Outlets and Actions The finished application is going to consist of a user interface comprising a UITextView and UIButton The user will enter text into the text view and initiate the saving of that text to a file by touching the button As such the view controller will require an outlet to the text view object and an action method to be called by the button With these requirements in mind select the iCloudStoreViewController h file and modify it to add the action and outlet import UIKit UIKit h interface iCloudStoreViewController UIViewController property strong nonatomic IBOutlet UITextView textView IBAction saveDocument end Next select the iCloudStoreViewController m implementation file and add the synthesize directive for the outlet the declaration of the action method and the code to ensure the outlet gets released by the ARC when no longer needed import iCloudStoreViewController h interface iCloudStoreViewController end implementation iCloudStoreViewController synthesize textView void saveDocument void viewDidUnload super viewDidUnload Release any retained subviews of the main view e g self myOutlet nil self textView nil end Now that the action and outlet are declared now is a good time to design the user interface of the application and make the appropriate connections Designing the User Interface As previously stated the user interface is going to consist of a UITextView and a UIButton Select iCloudStoreViewController xib and display the Interface Builder Object Library View Utilities Show Object Library Drag and drop the Text View and Round Rect Button objects into the view canvas resizing the text view so that it occupies only the upper area of the view Double click on the button object and change the label text to Save Figure 34 1 Remove the example Latin text from the text view object by selecting it in the view canvas and deleting the value from the Text property in the Attribute Inspector panel With the user interface designed it is now time to connect the action and outlet Ctrl click on the button object and drag the resulting line to the File s Owner entry in the center panel From the resulting menu select the saveDocument action method To connect the outlet Ctrl click on the File s Owner icon and drag the resulting line to the Text View object Release the line and select textView from the menu 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 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 Foundation Foundation h interface MyDocument UIDocument property strong nonatomic NSString userText end Edit the MyDocument m file and add the corresponding synthesize directive import MyDocument h implementation MyDocument synthesize 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 contentForType method as follows id contentsForType NSString typeName error NSError autoreleasing outError return NSData dataWithBytes self userText UTF8String length self 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 self userText NSString alloc initWithBytes contents bytes length contents length encoding NSUTF8StringEncoding else self userText return YES The implementation of the MyDocument class is now complete and it is time to begin implementing the application functionality Loading the Document at App Launch The ultimate goal of the application is to save any text in the text view to a document on the local file system of the device When the application is launched it needs to check if the document exists and if so load the contents into the text view object If on the other hand the document does not yet exist it will need to be created As is usually the case the best place to perform these tasks is the viewDidLoad method of the view controller Before implementing the code for the viewDidLoad method we first

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

  • Using iCloud Storage in an iOS 5 iPad Application - Techotopia
    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 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 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

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



  •