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".
  • An Example iOS 9 UIPageViewController Application - Techotopia
    String baseURL NSURL string At this point work on the content view controller is complete The next step is to create the data model for the application Creating the Data Model The data model for the application is going to consist of an array object containing a number of string objects each configured to contain slightly different HTML content For the purposes of this example the data source for the UIPageViewController instance will be the application s ViewController class This class will therefore need references to an NSArray and a UIPageViewController object It will also be necessary to declare this class as implementing the UIPageViewControllerDataSource and UIPageViewControllerDelegate protocols Select the ViewController swift file and add these references as follows import UIKit class ViewController UIViewController UIPageViewControllerDataSource UIPageViewControllerDelegate var pageController UIPageViewController var pageContent NSArray The final step in creating the model is to add a method to the ViewController swift file to add the HTML strings to the array and then call that method from viewDidLoad import UIKit class ViewController UIViewController UIPageViewControllerDataSource UIPageViewControllerDelegate override func viewDidLoad super viewDidLoad createContentPages func createContentPages var pageStrings String for i in 1 11 let contentString html head head body br h1 Chapter i h1 p This is the page i of content displayed using UIPageViewController in iOS 9 p body html pageStrings append contentString pageContent pageStrings eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters The application now has a content view controller and a data model from which the content of each page will be extracted by the data source methods The next logical step therefore is to implement those data source methods As previously outlined in Implementing a Page based iOS 9 Application with UIPageViewController instances of the UIPageViewController class need a data source This takes the form of two methods one of which is required to return the view controller to be displayed after the currently displayed view controller and the other the view controller to be displayed before the current view controller Since the ViewController class is going to act as the data source for the page view controller object these two methods together with two convenience methods which we will borrow from the Xcode Page based Application template will need to be added to the ViewController swift file Begin by adding the two convenience functions func viewControllerAtIndex index Int ContentViewController if pageContent count 0 index pageContent count return nil let storyBoard UIStoryboard name Main bundle NSBundle mainBundle let dataViewController storyBoard instantiateViewControllerWithIdentifier contentView as ContentViewController dataViewController dataObject pageContent index return dataViewController func indexOfViewController viewController ContentViewController Int if let dataObject AnyObject viewController dataObject return pageContent indexOfObject dataObject else return NSNotFound The viewControllerAtIndex method begins by checking to see if the page being requested is outside the bounds of available pages by checking if the index reference is zero the user cannot page back beyond

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


  • Working with Directories in Swift on iOS 9 - Techotopia
    For example the following code fragment identifies the current working directory let currentPath filemgr currentDirectoryPath Identifying the Documents Directory Each 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 iPhone or 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 a Swift 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 let dirPaths NSSearchPathForDirectoriesInDomains DocumentDirectory UserDomainMask true let docsDir dirPaths 0 as String When executed the above code will assign the path to the Documents directory to the docsDir constant When executed within the iOS Simulator environment the path returned will take the form of Users user name Library Developer CoreSimulator Devices device id data Containers Data Application 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 device id is the unique ID of the device on which the app is running and app id is the unique ID of the app for example eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters 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 applications When executed on a physical iOS device however the path returned by the function call will take the following form var mobile Containers Data Application app id Documents Identifying the Temporary Directory In addition to the Documents directory iOS 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 to the NSTemporaryDirectory C function as follows let tmpDir NSTemporaryDirectory as String Once executed the string object referenced by tmpDir will contain the path to the temporary directory for the application eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook

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

  • Working with Files in Swift on iOS 9 - Techotopia
    a Boolean return value var error NSError if filemgr removeItemAtPath filepath1 error error println Remove successful else println Remove failed error localizedDescription 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 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 var error NSError if filemgr createSymbolicLinkAtPath filepath2 withDestinationPath filepath1 error error println Link successful else println Link failed error localizedDescription 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 First the contents of a file may be read and stored in an NSData object through the use of the contentsAtPath method let databuffer filemgr contentsAtPath filepath1 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 filemgr createFileAtPath filepath2 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 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 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 the following code excerpt opens a file for reading and then closes it without actually doing anything to the file let file NSFileHandle NSFileHandle forReadingAtPath filepath1 if file nil println File open failed else file closeFile NSFileHandle File Offsets and Seeking NSFileHandle objects maintain

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

  • IOS 9 Directory Handling and File I/O in Swift – A Worked Example - Techotopia
    as illustrated in Figure 35 1 Figure 40 1 Shift click on the Text Field and Button so that both views are selected and use the Auto Layout Align menu to add a Horizontal Center in Container constraint Select only the Text Field view and use the Auto Layout Pin menu to add a Spacing to nearest neighbor constraint on the top edge of the view and enable the Width constraint After adding these constraints select the Button view and use the Pin menu once again to add a Spacing to nearest neighbor constraint on the top edge of the view Select the 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 textBox 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 saveText eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters 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 field 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 ViewController swift file declare some variables that will be needed in the code and scroll down to the viewDidLoad method and edit it as follows import UIKit class ViewController UIViewController IBOutlet weak var textBox UITextField var fileMgr NSFileManager NSFileManager defaultManager var docsDir String var dataFile String override func viewDidLoad super viewDidLoad let dirPaths NSSearchPathForDirectoriesInDomains DocumentDirectory UserDomainMask true docsDir dirPaths 0 as String dataFile docsDir stringByAppendingPathComponent datafile dat if fileMgr fileExistsAtPath dataFile let databuffer fileMgr contentsAtPath dataFile var datastring NSString data databuffer encoding NSUTF8StringEncoding textBox text datastring as String 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 create an instance of the NSFileManager class Because each iOS application on a device has its own Documents directory we next make the appropriate calls to identify the path to that directory and assign the result to the docsDir

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

  • Preparing an iOS 9 App to use iCloud Storage - Techotopia
    This provides a way for users to store private data and access it from multiple devices and also for the developer to provide data that is publicly available to all the users of an application CloudKit data storage is covered in detail beginning with the chapter entitled An Introduction to CloudKit Data Storage on iOS 9 Preparing an Application to Use iCloud Storage In order for an application to be able to use iCloud services it must be code signed with an App ID with iCloud support enabled In addition to enabling iCloud support within the App ID the application itself must also be configured with specific entitlements to enable one or both of the two iCloud storage methods outlined in the preceding section of this chapter Fortunately both of these tasks can be performed within the Capabilities screen within Xcode 7 Clearly iOS developers who are not yet members of the iOS Developer Program will need to enroll before implementing any iCloud functionality Details on enrolling in this program are outlined in the Joining the Apple Developer Program chapter of this book eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Enabling iCloud Support for an iOS 9 Application In order to enable iCloud support for an application load the project into Xcode and select the application name target from the top of the project navigator panel From the resulting project settings panel select the Capabilities tab and locate and switch on iCloud support as outlined in Figure 41 1 selecting a Development Team to use for the provisioning profile if prompted to do so Figure 41 1 The iCloud capabilities section provides options to enable key value storage iCloud Documents and CloudKit services Enabling iCloud support will have automatically added the iCloud entitlement to the application s App ID and also created an entitlements file to the project containing the application s iCloud container identifiers Reviewing the iCloud Entitlements File Once iCloud capabilities have been enabled for an application within Xcode a new file will appear in the project named product name entitlements 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 this entitlements file 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 icloud 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 requests are stored in a key value format The keys are the entitlement identifiers outlined

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

  • Managing Files using the iOS 9 UIDocument Class - Techotopia
    Editor panel and verify that the editor is displaying the contents of the ViewController swift file Ctrl click on the Text View object and drag to a position just below the class ViewController declaration line in the Assistant Editor Release the line and in the resulting connection dialog establish an outlet connection named textView Finally Ctrl click on the button object and drag the line to the area immediately beneath the viewDidLoad method declaration 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 eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters 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 swift file and add a declaration for a String object import UIKit class MyDocument UIDocument var userText String Some Sample Text 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 String object put it into an NSData object and return it Select the MyDocument swift file and add the contentsForType method as follows override func contentsForType typeName String throws AnyObject if let content userText let length content lengthOfBytesUsingEncoding NSUTF8StringEncoding return NSData bytes content length length else return NSData Implementing the

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

  • Using iCloud Storage in an iOS 9 Application - Techotopia
    search for and defining a ubiquitous search scope in other words instructing the object to search within the Documents directory of the app s iCloud storage area 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 predicate NSPredicate format K like savefile txt NSMetadataItemFSNameKey metaDataQuery searchScopes NSMetadataQueryUbiquitousDocumentsScope NSNotificationCenter defaultCenter addObserver self selector metadataQueryDidFinishGathering name NSMetadataQueryDidFinishGatheringNotification object metaDataQuery metaDataQuery startQuery Once the startQuery method is called the search will run and call 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 override func viewDidLoad super viewDidLoad let filemgr NSFileManager defaultManager ubiquityURL filemgr URLForUbiquityContainerIdentifier nil guard ubiquityURL nil else print Unable to access iCloud Account print Open the Settings app and enter your Apple ID into iCloud settings return ubiquityURL ubiquityURL URLByAppendingPathComponent Documents savefile txt metaDataQuery NSMetadataQuery metaDataQuery predicate NSPredicate format K like savefile txt NSMetadataItemFSNameKey metaDataQuery searchScopes NSMetadataQueryUbiquitousDocumentsScope NSNotificationCenter defaultCenter addObserver self 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 Documents directory of 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 eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters let query NSMetadataQuery notification object as NSMetadataQuery query disableUpdates NSNotificationCenter defaultCenter removeObserver self name NSMetadataQueryDidFinishGatheringNotification object query query stopQuery The next step is to extract the array of documents located during the search let results 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

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

  • Synchronizing iOS 9 Key-Value Data using iCloud - Techotopia
    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 eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters 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 Before starting on this project it is important to note that membership to the Apple Developer Program will be required as outlined in Joining the Apple Developer Program 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 44 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 iCloud Key Value Store 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 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 44 2 Figure 44 2 Click on the background View component in the layout display

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



  •