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 iOS 8 CloudKit Subscription Example - Techotopia
    or not a badge should be displayed on the application s launch icon Once the CKSubscription is fully configured it is committed to the cloud database using the saveSubscription method of the cloud database object For the purposes of this example the code to implement the subscription should be implemented in the viewDidLoad method located in the ViewController swift file override func viewDidLoad super viewDidLoad publicDatabase container publicCloudDatabase let predicate NSPredicate format TRUEPREDICATE let subscription CKSubscription recordType Houses predicate predicate options FiresOnRecordCreation let notificationInfo CKNotificationInfo notificationInfo alertBody A new House was added notificationInfo shouldBadge true subscription notificationInfo notificationInfo publicDatabase saveSubscription subscription completionHandler returnRecord error in if let err error println subscription failed err localizedDescription else dispatch async dispatch get main queue self notifyUser Success message Subscription set up successfully Note that the NSPredicate object was created using TRUEPREDICATE This is a special value that configures the predicate to always return a true value and is the equivalent of indicating that all records of the specified type match the predicate The FiresOnRecordCreation option indicates that the user is to be notified whenever a new record of type Houses is added to the database Other options available are FiresOnRecordUpdate FiresOnRecordDelete and FiresOnce The FiresOnce option causes the subscription to be deleted from the server after it has fired for the first time Compile and run the application on a device or simulator then log into the iCloud Dashboard Display the settings for the CloudKitDemo application and select the Subscription Types entry in the left hand navigation panel If the subscription was successfully configured it should be listed as shown in Figure 47 1 Figure 47 1 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 Handling Remote Notifications When the user selects a notification alert on an iOS device the CloudKitDemo application will be launched by the operating system At the point that the user selects the notification the application will currently be in one of three possible states foreground background or not currently running If the application is in the background when the alert is selected it is simply brought to the foreground If it was not currently running the application is launched by the operating system and brought to the foreground When the application is already in foreground or background state when a CloudKit notification alert is selected the didReceiveRemoteNotification method of the application delegate class is called and passed as an argument an NSDictionary instance containing a CKNotification object which contains among other information the ID of the cloud database record that triggered the notification If the application was not already in the foreground or background when the alert is selected the didReceiveRemoteNotification method is not called Instead information about the database change is passed as an argument to the didFinishLaunchingWithOptions method of the application delegate Implementing the

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


  • An Overview of iOS 8 Multitouch, Taps and Gestures - Techotopia
    in the 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 override func touchesBegan touches Set NSObject withEvent event UIEvent self nextResponder 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_8_Multitouch,_Taps_and_Gestures (2016-02-13)
    Open archived version from archive

  • An Example Swift iOS 8 Touch, Multitouch and Tap Application - Techotopia
    are ready to start writing the code for our application Designing the User Interface Load the storyboard by selecting the Main storyboard file Using Interface Builder modify the user interface by adding label components from the Object Library View Utilities Show Object Library and modifying properties until the view appears as outlined in Figure 49 1 When adding the rightmost labels be sure to stretch them so that the right hand edges reach approximately three quarters across the overall layout width Figure 49 1 Select label to the right of the Method label display the Assistant Editor panel and verify that the editor is displaying the contents of the ViewController swift file Ctrl click on the same label 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 methodStatus Repeat the above steps to establish outlet connections for the remaining label objects to properties named touchStatus and tapStatus Enabling Multitouch on the View By default views are configured to respond to only single touches in other words a single finger touching or tapping the screen at any one time For the purposes of this example we plan to detect multiple touches In order to enable this support it is necessary to change an attribute of the view object To achieve this click on the background of the View window display the Attributes Inspector View Utilities Show Attributes Inspector and make sure that the Multiple Touch option is selected in the Interaction section Figure 49 2 Implementing the touchesBegan Method When the user touches the screen the touchesBegan method of the first responder is called In order to capture these event types we need to implement this method in our view controller In the Xcode project navigator select the ViewController swift file and add the touchesBegan method as follows override func touchesBegan touches Set NSObject withEvent event UIEvent let touchCount touches count let touch touches first as UITouch let tapCount touch tapCount methodStatus text touchesBegan touchStatus text touchCount touches tapStatus text tapCount taps This method obtains a count of the number of touch objects contained in the touches set essentially the number of fingers touching the screen and assigns it to a variable It then gets the tap count from one of the touch objects The code then updates the methodStatus label to indicate that the touchesBegan method has been triggered constructs a string indicating the number of touches and taps detected and displays the information on the touchStatus and tapStatus labels accordingly Implementing the touchesMoved Method When the user moves one or more fingers currently in contact with the surface of the touch screen the touchesMoved method is called repeatedly until the movement ceases In order to capture these events it is necessary to implement the touchesMoved method in our view controller class override func touchesMoved touches Set NSObject withEvent event UIEvent let touchCount touches count let touch touches first

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

  • Detecting iOS 8 Touch Screen Gesture Motions in Swift - Techotopia
    TouchMotion select the Universal device setting and choose Swift as the programming language Designing the Application User Interface The application will display the X and Y coordinates of the touch and update these values in real time as the finger moves across the screen When the finger is lifted from the screen the start and end coordinates of the gesture will then be displayed on two label objects in the user interface Select the Main storyboard file and using Interface Builder create a user interface such that it resembles the layout in Figure 50 1 Figure 50 1 Be sure to stretch the labels so that they both extend to cover a little over half of the width of the view layout Select the top label 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 same label 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 xCoord Repeat this step to establish an outlet connection to the second label object named yCoord Next review the ViewController swift file to verify that the outlets are correct import UIKit class ViewController UIViewController IBOutlet weak var xCoord UILabel IBOutlet weak var yCoord UILabel 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 touchesBegan Method When the user first touches the screen the location coordinates need to be saved in the startPoint variable and those coordinates reported to the user This can be achieved by implementing the touchesBegan method in the ViewController swift file as follows override func touchesBegan touches NSSet withEvent event UIEvent let theTouch touches anyObject as UITouch var startPoint theTouch locationInView self view let x startPoint x let y startPoint y xCoord text x x yCoord text y y Implementing the touchesMoved Method When the user s finger moves across the screen the touchesMoved event will be called repeatedly until the motion stops By implementing the touchesMoved method in our view controller therefore we can detect the motion and display the revised coordinates to the user override func touchesMoved touches NSSet withEvent event UIEvent let theTouch touches anyObject as UITouch var touchLocation theTouch locationInView self view let x touchLocation x let y touchLocation y xCoord text x x yCoord text y y Implementing the touchesEnded Method When the user s finger lifts from the screen the touchesEnded method of the first responder is called The final task therefore is to implement this method in our view controller such that it displays the end point of the gesture override func touchesEnded touches NSSet withEvent event UIEvent let theTouch touches anyObject as UITouch var endPoint theTouch locationInView self view let

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

  • Identifying Gestures using iOS 8 Gesture Recognizers - Techotopia
    Identifies when the user makes a rotation gesture essentially two fingers in contact with the screen located opposite each other and moving in a circular motion UILongPressGestureRecognizer Used to identify when the user touches the screen with one or more fingers for a specified period of time also referred to as touch and hold These gesture recognizers must be attached to the view on which the gesture will be performed via a call to the view object s addGestureRecognizer method Recognizers must also be assigned an action method that is to be called when the specified gesture is detected Gesture recognizers may subsequently be removed from a view via a call to the view s removeGestureRecognizer method passing through as an argument the recognizer to be removed Recognizer Action Messages The iOS gesture recognizers use the target action model to notify the application of the detection of a specific gesture When an instance of a gesture recognizer is created it is provided with the reference to the method to be called in the event that the corresponding gesture is detected Discrete and Continuous Gestures Gestures fall into two distinct categories discrete and continuous A discrete gesture results in only a single call being made to the corresponding action method Tap gestures including multiple taps are considered to be discrete because they only trigger the action method once Gestures such as swipes pans rotations and pinches are deemed to be continuous in that they trigger a constant stream of calls to the corresponding action methods until the gesture ends Obtaining Data from a Gesture Each gesture action method is passed as an argument a UIGestureRecognizer sender object which may be used to extract information about the gesture For example information about the scale factor and speed of a pinch gesture may be obtained by the action method Similarly the action method assigned to a rotation gesture recognizer may ascertain the amount of rotation performed by the user and the corresponding velocity Recognizing Tap Gestures Tap gestures are detected using the UITapGestureRecognizer class This must be allocated and initialized with an action selector referencing the method to be called when the gesture is detected The number of taps that must be performed to constitute the full gesture may be defined by setting the numberOfTapsRequired property of the recognizer instance The following code for example will result in a call to the tapsDetected method when two consecutive taps are detected on the corresponding view let doubleTap UITapGestureRecognizer target self action tapDetected doubleTap numberOfTapsRequired 2 self view addGestureRecognizer doubleTap A template method for the action method for this and other gesture recognizers is as follows func tapDetected Code to respond to gesture here Recognizing Pinch Gestures Pinch gestures are detected using the UIPinchGestureRecognizer class For example let pinchRecognizer UIPinchGestureRecognizer target self action pinchDetected self view addGestureRecognizer pinchRecognizer Detecting Rotation Gestures Rotation gestures are recognized by the UIRotationGestureRecognizer the sample code for which is as follows let rotationRecognizer UIRotationGestureRecognizer target self action rotationDetected self view

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

  • An iOS 8 Swift Gesture Recognition Tutorial - Techotopia
    Figure 52 1 Select the label 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 same label 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 statusLabel Next the non visual gesture recognizer objects need to be added to the design Scroll down the list of objects in the Object Library panel until the Tap Gesture Recognizer object comes into view Drag and drop the object onto the View in the design area if the object is dropped outside the view the connection between the recognizer and the view on which the gestures are going to be performed will not be established Repeat these steps to add Pinch Rotation Swipe and Long Press Gesture Recognizer objects to the design Note that the document outline panel which can be displayed by clicking on the panel button in the lower left hand corner of the storyboard panel has updated to reflect the presence of the gesture recognizer objects as illustrated in Figure 52 2 An icon for each recognizer added to the view also appears within the toolbar across the top of the storyboard scene Figure 52 2 Within the document outline panel select the Tap Gesture Recognizer instance and display the Attributes Inspector View Utilities Show Attributes Inspector Within the attributes panel change the Taps value to 2 so that only double taps are detected 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 Similarly select the Long Press Recognizer object and change the Min Duration attribute to 3 seconds Having added and configured the gesture recognizers the next step is to connect each recognizer to its corresponding action method Display the Assistant Editor and verify that it is displaying the content of ViewController swift Ctrl click on the Tap Gesture Recognizer object either in the document outline panel or in the scene toolbar 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 configured to call a method named tapDetected with the Type value set to UITapGestureRecognizer as illustrated in Figure 52 3 Figure 52 3 Repeat these steps to establish action connections for the pinch rotation swipe and long press gesture recognizers to methods named pinchDetected rotationDetected swipeDetected and longPressDetected respectively taking care to select the corresponding type value for each action Implementing the Action Methods Having configured the gesture recognizers the next step is to add code to the action methods that will be called by each recognizer when the corresponding gesture is detected The methods stubs

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

  • Implementing TouchID Authentication in iOS 8 Apps - Techotopia
    a reply closure expression called once the user has provided input context evaluatePolicy LAPolicy DeviceOwnerAuthenticationWithBiometrics localizedReason Authentication is required for access reply success error in Code to handle reply here The reply closure expression is passed a Boolean value indicating the success or otherwise of the authentication and an NSError object from which the nature of any failure can be identified via the corresponding error code Failure to authenticate will fall into one of the following three categories LAError SystemCancel The authentication process was cancelled by the operating system This error typically occurs when the application is placed in the background LAError UserCancel The authentication process was cancelled by the user LAError UserFallback The user opted to authenticate using a password instead of using TouchID In the event of the user fallback it is the responsibility of the application to prompt for and verify a password before providing access If the authentication process is successful however the application should provide the user with access to whatever screens data or functionality were being protected A TouchID Example Project Launch Xcode and create a new iOS Universal Single View Application project named TouchID using Swift as the programming language Select the Main storyboard file and drag and drop a Button view so that it is positioned in the center of the storyboard scene Double click on the button and change the text so that it reads Test TouchID With the button still selected display the Auto Layout Align menu and configure both horizontal and vertical Center in Container constraints Finally display the Assistant Editor and Ctrl click and drag from the button view to a position just beneath the viewDidLoad method in the ViewController swift file Release the line and in the connection dialog establish an Action connection to a method named testTouchID On completion of the user interface design the layout should resemble Figure 53 1 Figure 53 1 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Checking for TouchID Availability With the user interface designed the next step is to add some code to the testTouchID function to verify that the device can handle TouchID authentication Select the ViewController swift file import the LocalAuthentication Framework and add code to the testTouchID method as follows import UIKit import LocalAuthentication class ViewController UIViewController override func viewDidLoad super viewDidLoad Do any additional setup after loading the view typically from a nib IBAction func testTouchID sender AnyObject let context LAContext var error NSError if context canEvaluatePolicy LAPolicy DeviceOwnerAuthenticationWithBiometrics error error Device can use TouchID else Device cannot use TouchID switch error code case LAError TouchIDNotEnrolled rawValue notifyUser TouchID is not enrolled err error localizedDescription case LAError PasscodeNotSet rawValue notifyUser A passcode has not been set err error localizedDescription default notifyUser TouchID not available err error localizedDescription Before proceeding implement the notifyUser method

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

  • An Overview of iOS 8 Collection View and Flow Layout - Techotopia
    assigned to the collection view Instances of UICollectionViewCell class are not typically instantiated directly in code Instead the class is registered as the cell class for a collection view and is then created internally as needed Collection views are scrollable and consequently at any one time only a subset of the cells in a collection are visible This enables the system to reuse cell objects that are currently scrolled outside of the viewable area of the screen and only create new ones when necessary This is achieved using a queuing mechanism and results in improved performance particularly when dealing with larger data sets The UICollectionReusableView Class The base class from which the UICellCollectionView class is derived this class is most typically subclassed in application code to create supplementary views The UICollectionViewFlowLayout Class The UICollectionViewFlowLayout class is the default layout class for collection views and is designed to layout cells in a grid like manner This class requires a delegate object that conforms to the UICollectionViewDelegateFlowLayout protocol which is typically the collection view s UICollectionViewDelegate object By default flow is implemented in a manner similar to that of line wrapping in a text editor When one row of cells is full the cells flow onto the next row and so on until all cells capable of fitting into the currently visible display region are visible The flow layout class supports both horizontal and vertical scrolling configurable via the scrollDirection property In addition properties such as the spacing between lines of cells in the grid and cells in a row may be configured together with default sizes for cells and supplementary views unless overridden via methods implemented in the delegate object The UICollectionViewLayoutAttributes Class Each item in a collection view be it a cell or a supplementary view has associated with it a set of attributes The UICollectionViewLayoutAttributes class serves as an object into which these attributes can be stored and transferred between objects A Flow Layout object will for example be asked by the collection view object to return the attributes for a cell at a given index in a collection view via a call to the layoutAttributesForItemAtIndexPath method This method in turn returns those attributes encapsulated in a UICollectionViewLayoutAttributes object Similarly such object instances can be used to apply new attributes to a collection view element The attributes stored by the UICollectionViewLayoutAttributes class are as follows keeping in mind that this class may be subclassed and extended to allow the storage of other values alpha the transparency of the item center the location of the center of the item frame the CGRect frame in which the item is displayed hidden whether or not the item is currently visible indexPath the index path location of the item in the collection view representedElementCategory The type of item for which the attributes apply i e for a cell supplementary or decoration view size the size of the item transform3D the current transform of the item This attribute can be used to perform tasks such as rotating or scaling the item zIndex controls the position of the item in the z axis in other words whether or not it is on top of or below other overlapping items 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 The UICollectionViewDataSource Protocol The UICollectionViewDataSource protocol needs to be implemented by the class responsible for supplying the collection view with the pre configured cells and supplementary views to be displayed to the user This basically consists of a number of methods that define information such as how many items of data are to be displayed how the data is divided into different sections and most importantly supplies the collection view with the cell objects to be displayed Mandatory methods in the protocol are as follows collectionView numberOfItemsInSection Returns the number of items to be displayed in the specified section of the collection view collectionView cellForItemAtIndexPath This method is called by the collection view when it is ready to display a cell at the specified index path location in the collection view It is required to return a cell object configured appropriately for the referenced index Optional methods in the protocol are as follows numberOfSectionsInCollectionView Indicates to the collection view the number of sections into which the collection view is to be divided collectionView viewForSupplementaryElementOfKind atIndexPath Called by the collection view to request a supplementary view of the specified kind Returns an appropriately configured object to be displayed In terms of the UICollectionViewFlowLayout class the layout will request a supplementary view for either a header UICollectionElementKindSectionHeader or footer UICollectionElementKindSectionFooter The UICollectionViewDelegate Protocol The UICollectionViewDelegate protocol defines a set of optional methods which if implemented will be called when certain events take place within the corresponding collection These methods relate primarily to handling user interaction with the collection view elements such as selecting a specific cell Some of the key methods in this protocol include collectionView shouldSelectItemAtIndexPath Returns a boolean value indicating whether the specified item is selectable by the user collectionView didSelectItemAtIndexPath Called by the collection view when the specified item has been selected by the user collectionView shouldDeselectItemAtIndexPath Returns a boolean value to indicate whether the specified item may be deselected by the user collectionView didDeselectItemAtIndexPath Called by the collection view when the specified item has been selected by the user collectionView shouldHighlightItemAtIndexPath Returns a boolean value indicating whether the specified item should be highlighted as a pre cursor to possible selection by the user collectionView didHighlightItemAtIndexPath Called by the collection view when the specified item has been highlighted collectionView didUnhighlightItemAtIndexPath Called by the collection view when the specified item has been un highlighted collectionView didEndDisplayingCell forItemAtIndexPath Called by the collection view when the specified cell has been removed from the collection view collectionView didEndDisplayingSupplementaryView forElementOfKind atIndexPath Called by the collection view when the specified supplementary

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



  •