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".
  • Working with Images in WatchKit - Techotopia
    WKInterfaceImage object would read as follows myImage setImageNamed spaceship Caching Extension based Images on the Watch Device As previously discussed images either reside on the Apple Watch device or originate within the WatchKit extension and reside on the paired iPhone device Images that reside on the iPhone device must be transferred to the watch device before they can be displayed to the user This problem can be alleviated to a certain extent by bundling images as named images as part of the WatchKit app bundle Situations may arise however where the images to be displayed are not known until app runtime such as when the image is selected or created dynamically within the WatchKit extension based on user activity In this case there is no option but to transfer the images to the device as the app is running The impact of the transfer of images can be reduced by caching them on the watch prior to the point at which the images are needed Images can be cached onto the paired Apple Watch using the addCachedImage and addCachedImageWithData methods of the WKInterfaceDevice object Each WatchKit app has 5MB of cache space available so caching should be used sparingly When the cache for an app is exhausted images must be removed using the removeCachedImageWithName or removeAllCachedImages methods of the WKInterfaceDevice object Once an image has been cached it is considered to be a named image and may be displayed using the standard named image methods Once an image has been cached it will remain on the device until it is explicitly removed Compressing Large Images Whilst caching is a useful way to store on the watch device frequently used images that originate in the WatchKit extension this still does not address the issue that it can take a considerable amount of time to transfer a large image from the iPhone to the Apple Watch Consider a scenario in which the extension for a WatchKit app needs to display a photo that the user has taken using the iPhone camera Transferring such an image could take over two minutes to transfer wirelessly from the iPhone to the watch This is clearly an unacceptable amount of time to keep the user waiting In reality the image that is taken by the iPhone camera is orders of magnitude larger than is necessary to fit on the display of an Apple Watch In fact an image from the iPhone camera roll is measured in thousands of pixels while the display of even the largest Apple Watch model has a resolution of only 312 x 390 pixels Clearly there is significant opportunity for reducing the size of any large images before they are transferred to the Apple Watch for display There are a number of options for reducing the size of any images both in terms of dimensions and storage space before the transfer to the watch takes place The following code for example is useful for reducing the size of an image by a

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


  • A WatchKit Animated Image Tutorial - Techotopia
    locate the Image object in the Object Library panel and drag and drop it onto the main storyboard scene With the newly added image object selected display the Attributes Inspector and change both the Horizontal and Vertical position properties to Center so that the scene layout matches Figure 22 1 Figure 22 1 Display the Assistant Editor panel and establish an outlet connection from the Image object in the scene named imageObject Adding the Animation Sequence Images The animation sequence in this example consists of 40 PNG image files which combine to make up an animation of the planet Earth rotating These files can be found in the animation images folder of the sample code archive available for download from the following link http www ebookfrenzy com watchkit animation images zip Locate and select the Images xcassets entry listed under the AnimationApp WatchKit App folder within the Xcode Project Navigator panel Ctrl click in the left hand panel of the asset catalog and select the Import option from the resulting menu Within the file selection dialog navigate to and select the animation images folder and click on Open Once the images have been imported into the asset catalog a new image set will be created named animation images containing all of the animation sequence images Figure 22 2 With the images added to the asset catalog all that remains is to add some code in the interface controller class to create and initiate the animation eBookFrenzy com Purchase the fully updated watchOS 2 Swift 2 edition of this book in eBook 12 99 or Print 27 99 format watchOS 2 App Development Essentials Print and eBook ePub PDF Kindle editions contain 35 chapters Creating and Starting the Animated Image Locate and edit the InterfaceController swift file and modify the awakeWithContext

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

  • Working with Fonts and Attributed Strings in WatchKit - Techotopia
    user s current preferred content size category setting Having obtained the preferred font the next step is to use the font to render the text displayed on a Label or Button interface object As will be outlined in the next section this involves the use of attributed strings Understanding Attributed Strings To display text within a WatchKit app using a particular font it is necessary to use an attributed string Attributed strings are represented using the NSAttributedString and NSMutableAttributedString classes and allow text to be combined with attributes such as fonts and colors Having obtained a font object as outlined in the previous section the next task is to create a Dictionary object with a key set to NSFontAttributeName and the font object as the value This dictionary is then used to specify the attributes for an NSAttributedString instance The following code for example obtains a font object for the headline text style and uses it to create an attributed string that reads Apple Watch let headlineFont UIFont preferredFontForTextStyle UIFontTextStyleHeadline let fontAttribute NSFontAttributeName headlineFont let attributedString NSAttributedString string Apple Watch attributes fontAttribute Once an attributed string has been created it can be applied to Button and Label interface objects using the setAttributedTitle and setAttributedText methods respectively The following code for example displays the attributedString text from the above example on a Label object myLabel setAttributedText attributedString When executed text which reads Apple Watch will be rendered on the label referenced by the myLabel outlet using the headline font style sized according to the user s preferred content size setting as shown in Figure 23 3 Figure 23 3 The above example uses an attributed string to set one attribute for the entire text string In practice attributed strings can contain multiple attributes covering different ranges of characters within the string Multiple attributes within an attributed string require the use of the NSMutableAttributedString class Once an instance of this class has been created and initialized with a string the addAttribute method may be called to add attributes for ranges of characters in the string For the purposes of the example project this approach will be used to change the colors used to render the words Apple and Watch in the label in Figure 23 3 The code to achieve this reads as follows eBookFrenzy com Purchase the fully updated watchOS 2 Swift 2 edition of this book in eBook 12 99 or Print 27 99 format watchOS 2 App Development Essentials Print and eBook ePub PDF Kindle editions contain 35 chapters let headlineFont UIFont preferredFontForTextStyle UIFontTextStyleHeadline let fontAttribute NSFontAttributeName headlineFont let attributedText NSMutableAttributedString string Apple Watch attributes fontAttribute let firstRange NSRange location 0 length 5 let secondRange NSRange location 6 length 5 attributedText addAttribute NSForegroundColorAttributeName value UIColor greenColor range firstRange attributedText addAttribute NSForegroundColorAttributeName value UIColor redColor range secondRange myLabel setAttributedText attributedText The above code creates a mutable attributed string using the headline text style font Two range objects are then created and initialized to encompass the first and second words of

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

  • A WatchKit App Custom Font Tutorial - Techotopia
    the scene display the Attributes Inspector and change the Layout property to Vertical In the Position section of the attributes panel change both the Horizontal and Vertical menus to Center Drag and drop two Label objects from the Object Library panel onto the Group object in the scene layout Double click on the upper label and change the text so it reads Hello Shift click on each Label object so that both are selected and within the Attributes Inspector panel change the Horizontal position property to Center On completion of these steps verify that the scene matches the layout shown in Figure 24 4 Figure 24 4 The last task to perform within Interface Builder is to establish an outlet connection on the second Label object Display the Assistant Editor panel verify that it is displaying the content of the InterfaceController swift file and Ctrl click and drag from the lower Label to a position immediately beneath the class declaration line in the editor panel On releasing the line use the connection dialog to establish an outlet named labelObject Adding the Custom Font to the Project There are two steps to integrating a custom font into a WatchKit app The first step is to add the font file to the project For the purposes of this example the Sofia Regular font will be used Locate this font in the Finder window and drag and drop it onto the Supporting Files folder located beneath the CustomFont WatchKit App entry in the Xcode project navigator Figure 24 5 Since the font will need to be accessible to both the WatchKit App and the extension make sure that both targets are selected in the options panel Figure 24 6 before clicking on the Finish button Figure 24 6 In addition to adding the font file to the project and configuring the targets an entry for the font needs to be added to the Info plist files for both the WatchKit app and extension targets Begin by selecting the Info plist file located in the Supporting Files section of the CustomFont WatchKit App folder in the Project Navigator panel Once the file has loaded into the property list editor select the last row in the list so that it highlights in blue Click on the button that appears in the selected row to add a new entry to the list From the dropdown menu that appears scroll down to and select the Fonts provided by application option as illustrated in Figure 24 7 Figure 24 7 Click on the arrow to the left of the newly added row to list the first item in the array of fonts Double click in the Value column of this row to enter into editing mode type in the full file name of the custom font file including the otf filename extension and press the keyboard Enter key Figure 24 8 The same entry also needs to be added to the Info plist file of the extension target

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

  • Supporting Different Apple Watch Display Sizes - Techotopia
    watch model When running on the smaller 38mm watch model however the 14pt customization font attribute will be used It is worth noting that it is not necessary to also add a customization attribute for the 42mm font setting since this is covered by the default value Working with Screen Sizes in Interface Builder By default the storyboard editor in Interface Builder displays storyboard scenes in Any Screen Size mode When in this mode interface objects are displayed using the default attributes To see how the scenes within a storyboard will appear on different screen sizes this mode can be changed using the selection at the bottom of the storyboard editor panel as shown in Figure 25 4 Figure 25 4 Clicking on the button displays a menu of screen size options which when selected change the mode of the storyboard canvas to match the chosen screen size When a specific screen size mode is selected in Interface Builder the scenes in the canvas will update to reflect the size of the screen In addition the interface objects within the scenes will change to reflect any customization attributes that have been set for the selected screen size This allows you to review the user interface layout as it will appear when running on the designated Apple Watch model A more significant point to note about changing the storyboard screen size mode is that any changes made to the scene layout will apply only for the current screen size Consider for example a scene containing a label If the storyboard editor is in 38mm mode when the text of the label is changed within the scene then that change only applies to the layout when the app is running on a 38mm device In other words visually manipulating the objects and layout when the storyboard editor is set for a specific screen size essentially configures screen size customization attributes which also appear within the Attributes Inspector panel In Figure 25 5 for example the text displayed on a label has been changed to read My 42mm Text from within the scene canvas while the storyboard editor is in 42mm mode Note that as a result of this change a matching 42mm screen size customization attribute for the text property is now listed in the Attributes Inspector panel Figure 25 5 eBookFrenzy com Purchase the fully updated watchOS 2 Swift 2 edition of this book in eBook 12 99 or Print 27 99 format watchOS 2 App Development Essentials Print and eBook ePub PDF Kindle editions contain 35 chapters Clearly screen size customization attributes can be configured both manually by adding custom attributes via the Attributes Inspector panel and visually from within the storyboard editor by changing the screen size mode and directly manipulating the interface objects When the storyboard editor is in any mode other than Any Screen Size the toolbar at the bottom of the canvas is displayed in blue This is intended as a subtle reminder that any changes

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

  • A WatchKit Map Tutorial - Techotopia
    the WatchKit app the containing iOS app will be launched in the background The containing iOS app also needs to be configured therefore to allow background location updates to be received To enable this mode select the MapDemoApp target located at the top of the Project Navigator panel and make sure that the target menu in the settings panel is set to MapDemoApp as indicated in Figure 26 4 Figure 26 4 Select the Capabilities tab and enable the Background Modes option Once enabled activate support for Location updates by selecting the corresponding checkbox Figure 26 5 Handling the Open Parent App Request The steps outlined in the chapter entitled WatchKit App and Parent iOS App Communication will now be used to launch the parent iOS app obtain the user s current location and return that information to the WatchKit app extension The first step in this process is to implement the code in the app delegate of the iOS app to handle the launch request Select the AppDelegate swift file and begin by adding the handleWatchKitExtensionRequest method and declaring a variable in which to store the background request identifier value import UIKit import CoreLocation UIApplicationMain class AppDelegate UIResponder UIApplicationDelegate var window UIWindow let locationManager CLLocationManager var bgIdentifier UIBackgroundTaskIdentifier func application application UIApplication handleWatchKitExtensionRequest userInfo NSObject AnyObject reply NSObject AnyObject Void bgIdentifier application beginBackgroundTaskWithName MyTask expirationHandler Void in println Time expired As discussed in the WatchKit App and Parent iOS App Communication chapter one of the arguments passed through to the handleWatchKitExtensionRequest is a reference to the reply handler closure that is to be called in order to return data to the WatchKit extension The mechanism for obtaining location data in iOS operates in a way that will require us to call the reply handler closure from within another method of the app delegate class To make this possible it will be necessary to store a reference to the closure handler reference in a variable where it can be accessed by other methods in the class Remaining in the AppDelegate swift file therefore add a variable configured with the signature of the closure and a line of code to store the reference as follows import UIKit import CoreLocation UIApplicationMain class AppDelegate UIResponder UIApplicationDelegate var window UIWindow let locationManager CLLocationManager var bgIdentifier UIBackgroundTaskIdentifier var replyHandler NSObject AnyObject Void arg in func application application UIApplication handleWatchKitExtensionRequest userInfo NSObject AnyObject reply NSObject AnyObject Void replyHandler reply bgIdentifier application beginBackgroundTaskWithName MyTask expirationHandler Void in println Time expired Getting the Current Location The next step is to instruct the location manager to begin receiving location updates This involves declaring the AppDelegate class as implementing the CLLocationManagerDelegate protocol assigning the class as the delegate for the location manager and starting the location update process class AppDelegate UIResponder UIApplicationDelegate CLLocationManagerDelegate var window UIWindow let locationManager CLLocationManager var bgIdentifier UIBackgroundTaskIdentifier var replyHandler NSObject AnyObject Void arg in func application application UIApplication handleWatchKitExtensionRequest userInfo NSObject AnyObject reply NSObject AnyObject Void replyHandler reply bgIdentifier application beginBackgroundTaskWithName MyTask expirationHandler Void in

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

  • An Overview of Notifications in WatchKit - Techotopia
    Notifications are categorized as being either local or remote A local notification is typically initiated from within the containing iOS app A remote notification on the other hand is sent over the internet to the iPhone from a remote server As previously outlined a notification can appear either on the iPhone device or the paired Apple Watch When a notification action on an Apple Watch is selected by the user the handler method that gets called will depend on whether the notification was remote or local in origin and whether the notification action was configured for background or foreground mode When a remote notification appears on the Apple Watch and the user selects a background notification action the following method is called on the application delegate of the containing iOS app application handleActionWithIdentifier forRemoteNotification completionHandler If the notification is local however the following method will be called on the app delegate of the containing iOS app when a background action is selected application handleActionWithIdentifier forLocalNotification completionHandler When a remote notification appears on the Apple Watch and the user selects a foreground notification action the WatchKit app will launch and the following method on the main interface controller will be called handleActionWithIdentifier forRemoteNotification The same scenario involving a local notification on the Apple Watch will result in the following method being called on the main interface controller handleActionWithIdentifier forLocalNotification The topics of WatchKit notification handling and action notifications will be covered in further detail in the next chapter A WatchKit Notification Tutorial Custom Notifications The previously outlined default notification handling within WatchKit is somewhat limited in terms of customization options While it is possible to add action buttons to the notification when it is displayed to the user there is no control of the layout and content that is presented within the notification scene This shortcoming can be overcome however through the use of custom notifications Custom notifications allow the appearance of a notification category on the Apple Watch to be designed in terms of the interface objects that are presented to the user and the content that is displayed on those objects In fact a dynamic custom interface can contain any combination of non interactive interface objects such as Label Map and Image objects A custom notification is made up of two parts referred to as static and dynamic notifications eBookFrenzy com Purchase the fully updated watchOS 2 Swift 2 edition of this book in eBook 12 99 or Print 27 99 format watchOS 2 App Development Essentials Print and eBook ePub PDF Kindle editions contain 35 chapters Dynamic and Static Notifications Custom notifications consist of a static and a dynamic notification The static notification consists of a Label object which displays the content of the notification s alert body text The static notification scene can be customized by adding additional non interactive interface objects such as Labels and Images note that any images displayed on the static notification scene must be bundled with the WatchKit app and not the

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

  • A WatchKit Notification Tutorial - Techotopia
    the following listing func setNotification if let timeValue sharedDefaults doubleForKey timeDelay var localNotification UILocalNotification UILocalNotification localNotification alertTitle Reminder localNotification alertBody Wake Up localNotification fireDate NSDate timeIntervalSinceNow timeValue localNotification soundName UILocalNotificationDefaultSoundName localNotification category REMINDER CATEGORY UIApplication sharedApplication scheduleLocalNotification localNotification The setNotification method will need to be called each time that the user taps the Set Delay button which is configured to call the buttonPressed method Add the call to the setNotification method to the buttonPressed method IBAction func buttonPress sender AnyObject setNotification Adding the Notification Actions When the notification is triggered the user is to be given the option of repeating the notification using the same delay or adjusting the prevailing delay duration This will involve the addition of some notification actions to the notification using the REMINDER CATEGORY identifier referenced each time the notification is set The code to configure the actions will be placed within the Application Delegate class within the didFinishLaunchingWithOptions method Begin by locating and selecting the AppDelegate swift file and modifying the didFinishLaunchingWithOptions method to create the first notification action as follows func application application UIApplication didFinishLaunchingWithOptions launchOptions NSObject AnyObject Bool var repeatAction UIMutableUserNotificationAction UIMutableUserNotificationAction repeatAction identifier REPEAT IDENTIFIER repeatAction title Repeat repeatAction destructive false repeatAction authenticationRequired false repeatAction activationMode UIUserNotificationActivationMode Background return true The above code creates a new notification action instance and configures it with an identifier string this will be used to identify which action has been selected by the user later in the project The action is also configured to display text which reads Repeat on the action button and to indicate that it is a non destructive action in other words it does not cause the loss of any data or information In the event that the device is locked when the notification is triggered the action is configured such that it is not necessary for the user to unlock the device for the action to be performed Finally since the notification can be repeated without the need to display the iOS app the activation mode is set to Background mode Add the following code to the didFinishLaunchingWithOptions method beneath the code for the first action to create and configure the second action var modifyAction UIMutableUserNotificationAction UIMutableUserNotificationAction modifyAction identifier MODIFY IDENTIFIER modifyAction title Modify modifyAction destructive false modifyAction authenticationRequired false modifyAction activationMode UIUserNotificationActivationMode Foreground This time the action is configured with an identifier of MODIFY IDENTIFIER and to display Modify on the action button Since the iOS app will need to be displayed in order for the user to modify the time delay value the action is configured using Foreground mode The next task is to create the notification category containing the two actions and register it with the notification system func application application UIApplication didFinishLaunchingWithOptions launchOptions NSObject AnyObject Bool var repeatAction UIMutableUserNotificationAction UIMutableUserNotificationAction repeatAction identifier REPEAT IDENTIFIER repeatAction title Repeat repeatAction destructive false repeatAction authenticationRequired false repeatAction activationMode UIUserNotificationActivationMode Background var modifyAction UIMutableUserNotificationAction UIMutableUserNotificationAction modifyAction identifier MODIFY IDENTIFIER modifyAction title Modify modifyAction destructive false modifyAction authenticationRequired false modifyAction activationMode UIUserNotificationActivationMode Foreground var notificationCategory UIMutableUserNotificationCategory UIMutableUserNotificationCategory notificationCategory identifier REMINDER CATEGORY notificationCategory setActions repeatAction modifyAction forContext UIUserNotificationActionContext Default application registerUserNotificationSettings UIUserNotificationSettings forTypes UIUserNotificationType Sound UIUserNotificationType Alert UIUserNotificationType Badge categories NSSet array notificationCategory as Set NSObject return true Compile and run the app and allow notification access when prompted by the operating system Select a delay time and press the Set Delay button Once the delay has been set place the app into the background by pressing the Home button on the device or selecting the Hardware Home menu option within the simulator When the notification appears swipe downward on the alert panel to display the action buttons as shown in Figure 28 3 Figure 28 3 Tap the Modify button and verify that the iOS app launches Assuming that the app behaves as expected the next step is to handle the Repeat action eBookFrenzy com Purchase the fully updated watchOS 2 Swift 2 edition of this book in eBook 12 99 or Print 27 99 format watchOS 2 App Development Essentials Print and eBook ePub PDF Kindle editions contain 35 chapters Implementing the handleActionWithIdentifier Method When a notification action button configured for background mode is tapped by the user the handleActionWithIdentifier method of the app delegate class is called Among the items passed to the method are a notification object from which both the action and category identifiers of the action that triggered the call can be obtained together with a completion handler to be called once the action has been handled This method now needs to be added to the AppDelegate swift file along with a variable in which to store a reference to the view controller instance as follows UIApplicationMain class AppDelegate UIResponder UIApplicationDelegate var window UIWindow var viewController ViewController func application application UIApplication handleActionWithIdentifier identifier String forLocalNotification notification UILocalNotification completionHandler Void if identifier REPEAT IDENTIFIER notification category REMINDER CATEGORY viewController ViewController viewController setNotification completionHandler The method begins by verifying that the category and action id match the repeat action If this is a repeat action request an instance of the ViewController class is created and the setNotification method of the instance called to repeat the notification The completion handler block is then called to indicate that the action has been handled Re run the app set up a notification and place the app in the background Display the action buttons in the notification panel when it appears and tap on the Repeat button After the designated time has elapsed the notification should trigger a second time as requested Adding the WatchKit App to the Project Now that work on the iOS app is complete the next task is to add the WatchKit app to the project Within Xcode select the File New Target menu option In the target template dialog select the Apple Watch option listed beneath the iOS heading In the main panel select the WatchKit App icon and click on Next On the subsequent screen switch the Include Notification Scene and Include Glance Scene options off before

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



  •