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".
  • Implementing a Swift Page based iOS 8 Application using UIPageViewController - Techotopia
    data source which in turn is responsible for providing view controller objects as required for each page The data source takes the form of a class instance that implements the UIPageViewControllerDataSource protocol which at a minimum must implement the following two methods viewControllerAfterViewController This method is passed a view controller representing the currently displayed page and is required to return the view controller corresponding to the next page in the paging sequence viewControllerBeforeViewController This method is passed the view controller representing the currently displayed page and is required to return the view controller corresponding to the previous page in the paging sequence The mechanism used to create the requested view controllers and the content therein will generally be application specific and is at the discretion of the developer Apple does however recommend that in order to ensure optimal performance and minimal resource usage the view controllers be created on an as needed basis rather than pre created When a UIPageViewController object is initialized a number of configuration options may be specified to configure the appearance and behavior of the contained views 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 Navigation Orientation The page controller is capable of transitioning between views using either a vertical or horizontal paradigm In the case of horizontal navigation page transitions take place in the same way pages are turned in a physical book by sweeping a finger on the screen either left or right In the case of horizontal navigation pages are turned by making vertical gestures in much the same way the pages of a wall calendar are flipped These options are configured using the following constants UIPageViewControllerNavigationOrientation Horizontal UIPageViewControllerNavigationOrientation Vertical Spine Location The UIPageViewController class allows for the location of the spine to be configured The term spine in this context is analogous to the spine of a book and dictates the location of the axis on which each page will turn The behavior of the spine location settings vary depending on the navigation orientation setting For example the default for most configurations is UIPageViewControllerSpineLocation Min which places the spine on the left hand side or top of the screen depending on whether the navigation orientation is horizontal or vertical Similarly the UIPageViewControllerSpineLocation Max setting will position the spine at the right or bottom edge of the display In order to display two pages simultaneously the UIPageViewControllerSpineLocationMid setting should be used The view controller may also be configured to treat pages as being double sided via the doubleSided property Note that when using UIPageViewControllerSpineLocationMid spine location it will be necessary to provide the page controller with two view controllers one for the left hand page and one for the right for each page turn Similarly when using either the min or max spine location together with the double sided setting view

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


  • An Example Swift iOS 8 UIPageViewController Application - Techotopia
    to margins option switched off Select the Web View object in the storyboard panel display the Assistant Editor panel and verify that the editor is displaying the contents of the ContentViewController swift file Ctrl click on the web view 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 webView Figure 32 1 With the user interface designed select the ContentViewController swift file Each time the user turns a page in the application the data source methods for a UIPageViewController object are going to create a new instance of our ContentViewController class and set the dataObject property of that instance to the HTML that is to be displayed on the web view object As such the viewWillAppear method of ContentViewController needs to assign the value stored in the dataObject property to the web view object To achieve this behavior add the viewWillAppear method to assign the HTML to the web view import UIKit class ContentViewController UIViewController var dataObject AnyObject IBOutlet weak var webView UIWebView override func viewWillAppear animated Bool super viewWillAppear animated webView loadHTMLString dataObject as 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 8 p body html pageStrings append contentString pageContent pageStrings 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 8 Application using 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

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

  • Working with Directories in Swift on iOS 8 - Techotopia
    loads its current working directory is the application s root directory represented by a character The current working directory may be identified at any time by accessing the currentDirectoryPath property of the file manager object 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 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 fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12

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

  • Working with Files in Swift on iOS 8 - Techotopia
    an optional NSError object The success of the operation is as usual reported in the form of 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 google ADSDAQBOX FLOW google 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

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

  • IOS 8 Directory Handling and File I/O in Swift – A Worked Example - Techotopia
    text to Save Position the components and resize the width of the text field so that the layout appears as illustrated in Figure 35 1 Figure 35 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 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 variable Once we know where the documents directory is located we construct the full path to our file which

    Original URL path: http://www.techotopia.com/index.php/IOS_8_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 8 App to use iCloud Storage - Techotopia
    in a structured way 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 8 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 6 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 iOS Developer Program chapter of this book Enabling iCloud Support for an iOS 8 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 36 1 selecting a Development Team to use for the provisioning profile if prompted to do so Figure 36 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 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 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

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

  • Managing Files using the iOS 8 UIDocument Class - Techotopia
    the user interface designed it is now time to connect the action and outlet Select the Text View 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 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 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 NSString 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 error outError NSErrorPointer AnyObject if let content userText var length content lengthOfBytesUsingEncoding NSUTF8StringEncoding return NSData bytes content length length else return NSData Implementing the loadFromContents Method The loadFromContents instance method is called by an

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

  • Using iCloud Storage in an iOS 8 Application - Techotopia
    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 URLByAppendingPathComponent Documents ubiquityURL ubiquityURL URLByAppendingPathComponent 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 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 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 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 and used to create an instance of our MyDocument class called document The openWithCompletionHandler method of the document object is then called to open the document in the cloud and read the contents This will trigger a call to the loadFromContents method of the document object which in turn will assign the contents of the

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



  •