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".
  • A Swift Example iOS 8 Location Application - Techotopia
    UILabel IBOutlet weak var distance UILabel var locationManager CLLocationManager CLLocationManager var startLocation CLLocation Configuring the CLLocationManager Object The next task is to configure the instance of the CLLocationManager class and to make sure that the application requests permission from the user to track the current location of the device Since this needs to occur when the view loads an ideal location is in the view controller s viewDidLoad method in the ViewController swift file override func viewDidLoad super viewDidLoad locationManager desiredAccuracy kCLLocationAccuracyBest locationManager delegate self locationManager requestWhenInUseAuthorization locationManager startUpdatingLocation startLocation nil The above code changes configure the CLLocationManager object instance to use the best accuracy setting The code then declares the view controller instance as the application delegate for the location manager object The application then requests permission from the user for the application to track location information while the application is in the foreground prior to starting location updating via a call to the startUpdatingLocation method Since location tracking has just begun at this point the startLocation variable is also set to nil Setting up the Usage Description Key The above code changes included a method call to request permission from the user to track location information when the application is running in the foreground This method call must be accompanied by a usage description string which needs to be added to the project s Info plist file and assigned to the NSLocationWhenInUseUsageDescription key Within the project navigator panel load the Info plist file located under Supporting Files into the editor The key value pair needs to be added to the Information Property List dictionary Select this entry in the list and click on the button to add a new entry to the dictionary Within the new entry enter NSLocationWhenInUseUsageDescription into the key column and once the key has been added double click in the corresponding value column and enter the following text so that the entry matches that of Figure 75 2 The application uses this information to show you your location Figure 75 2 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 Action Method The button object in the user interface is connected to the resetDistance action method so the next task is to implement that action All this method needs to do is set the startlocation variable to nil IBAction func resetDistance sender AnyObject startLocation nil Implementing the Application Delegate Methods When the location manager detects a location change it calls the didUpdateToLocation delegate method Since the view controller was declared as the delegate for the location manager in the viewDidLoad method it is necessary to now implement this method in the ViewController swift file func locationManager manager CLLocationManager didUpdateLocations locations AnyObject var latestLocation AnyObject locations locations count 1 latitude text String format 4f latestLocation coordinate latitude longitude text String format 4f

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


  • Working with Maps on iOS 8 with Swift, MapKit and the MKMapView Class - Techotopia
    editor is displaying the contents of the ViewController swift file Ctrl click on the MKMapView 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 mapView Click on the Zoom button to select it note that in order to select a toolbar button item it may be necessary to click on it twice since the first click selects the toolbar parent With the button item selected 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 zoomIn Repeat this step to connect the Type button to a method named changeMapType Select the ViewController swift file from the project navigator panel and verify that the outlets and actions have been set up correctly Also take this opportunity to import the MapKit framework and to declare the class as implementing the MKMapViewDelegate protocol import UIKit import MapKit class ViewController UIViewController MKMapViewDelegate IBOutlet weak var mapView MKMapView override func viewDidLoad super viewDidLoad IBAction func zoomIn sender AnyObject IBAction func changeMapType sender AnyObject Perform a test run of the application s progress so far by clicking on the run button in the Xcode toolbar The application should run in the iOS simulator as illustrated in Figure 76 3 Figure 76 3 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 Obtaining Location Information Permission The next task is to request permission from the user to track the current location of the device Since this needs to occur when the application loads an ideal location is in the application delegate didFinishLaunchingWithOptions method in the AppDelegate swift file import UIKit import CoreLocation UIApplicationMain class AppDelegate UIResponder UIApplicationDelegate var window UIWindow var locationManager CLLocationManager func application application UIApplication didFinishLaunchingWithOptions launchOptions NSObject AnyObject Bool locationManager CLLocationManager locationManager requestWhenInUseAuthorization return true Setting up the Usage Description Key The above code changes included a method call to request permission from the user to track location information when the application is running in the foreground This method call must be accompanied by a usage description string which needs to be added to the project s Info plist file assigned to the NSLocationWhenInUseUsageDescription key Within the project navigator panel load the Info plist file located under Supporting Files into the editor The key value pair needs to be added to the Information Property List dictionary Select this entry in the list and click on the button to add a new entry to the dictionary Within the new entry enter NSLocationWhenInUseUsageDescription into the key column and once the key has been added double click

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

  • Working with MapKit Local Search in iOS 8 and Swift - Techotopia
    the first storyboard scene Begin by launching Xcode and opening the MapSample project created in the previous chapter Adding the Local Search Text Field With the project loaded into Xcode select the Main storyboard file and modify the user interface to add a Text Field object to the user interface layout reducing the height of the map view object accordingly to make room for the new field With the new Text Field selected display the Attributes Inspector and enter Local Search into the Placeholder property field When completed the layout should resemble that of Figure 77 1 Figure 77 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 Select the Map Sample view controller by clicking on the toolbar at the top of the scene so that the scene is highlighted in blue Select the Resolve Auto Layout Issues menu from the toolbar in the lower right hand corner of the storyboard canvas and select the Clear Constraints menu option Select the Text Field object and display the Auto Layout Pin menu Within the Spacing to Nearest Neighbor section configure constraints on all four sides of the view with the Constrain to margins option disabled and leaving the default settings unchanged as shown in Figure 77 2 Figure 77 2 Repeat the above steps to apply constraints on the Map View and Toolbar objects When the user touches the text field the keyboard will appear By default this will display a Return key For the purposes of this application however a Search key would be more appropriate To make this modification select the new Text Field object display the Attributes Inspector and change the Return Key setting from Default to Search Next display the Assistant Editor panel and make sure that it is displaying the content of the ViewController swift file Ctrl click on the Text Field object and drag the resulting line to the Assistant Editor panel and establish an outlet named searchText Repeat the above step this time setting up an Action for the Text Field to call a method named textFieldReturn for the Did End on Exit event The textFieldReturn method will be required to perform three tasks when triggered In the first instance it will be required to hide the keyboard from view When matches are found for the search results an annotation will be added to the map for each location The second task to be performed by this method is to remove any annotations created as a result of a previous search Finally the textFieldReturn method will initiate the search using the string entered into the text field by the user Select the ViewController swift file locate the template textFieldReturn method and implement it so that it reads as follows IBAction func textFieldReturn sender AnyObject sender resignFirstResponder mapView removeAnnotations mapView annotations self

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

  • Using MKDirections to get iOS 8 Map Directions and Routes - Techotopia
    that both are selected display the Auto Layout Resolve Auto Layout Issues menu and select the Reset to Suggested Constraints option listed under Selected Views Display the Assistant Editor make sure that it is displaying the ResultsTableCell swift file and then establish outlets from the two labels named nameLabel and phoneLabel respectively Next edit the ResultsTableViewController swift file and modify it to import the MapKit Framework and to declare an array into which will be placed the MKMapItem objects representing the local search results import UIKit import MapKit class ResultsTableViewController UITableViewController var mapItems MKMapItem Next edit the file to modify the data source and delegate methods so that the table is populated with the location information when displayed removing the warning lines during the editing process Note that the comment markers and will need to be removed from around the cellForRowAtIndexPath method override func numberOfSectionsInTableView tableView UITableView Int Return the number of sections return 1 override func tableView tableView UITableView numberOfRowsInSection section Int Int Return the number of rows in the section return mapItems count override func tableView tableView UITableView cellForRowAtIndexPath indexPath NSIndexPath UITableViewCell let cell tableView dequeueReusableCellWithIdentifier resultCell forIndexPath indexPath as ResultsTableCell Configure the cell let row indexPath row let item mapItems row cell nameLabel text item name cell phoneLabel text item phoneNumber return cell With the results table view configured the next step is to add a segue from the first scene to this scene Implementing the Result Table View Segue Select the Main storyboard file and drag and drop an additional Bar Button Item from the Object Library to the toolbar in the Map Sample View Controller scene Double click on this new button and change the text to Details Figure 78 3 Click on the Details button to select it it may be necessary to click twice since the first click will select the Toolbar Establish a segue by Ctrl clicking on the Details button and dragging to the Results Table View Controller and select show from the Action Segue menu When the segue is triggered the mapItems property of the ResultsTableViewController instance needs to be updated with the array of locations created by the local search This can be performed in the prepareForSegue method which needs to be implemented in the ViewController swift file as follows override func prepareForSegue segue UIStoryboardSegue sender AnyObject let destination segue destinationViewController as ResultsTableViewController destination mapItems self matchingItems With the Results scene complete compile and run the application on an iOS device Perform a search for a business type that returns valid results before selecting the Details toolbar button The results table should subsequently appear Figure 78 4 listing the names and phone numbers for the matching locations Figure 78 4 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 Adding the Route Scene The last task is to

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

  • An Introduction to Extensions in iOS 8 - Techotopia
    videos text and web sites within a host app with social network sites or content sharing services It is important to understand that Apple does not expect developers to write Share extensions designed to post content to destinations such as Facebook or Twitter such sharing options are already built into iOS but rather as a mechanism to make sharing easier for developers hosting their own sharing and social sites Share extensions appear within the activity view controller panel which is displayed when the user taps the Share button from within a host app Figure 79 2 for example shows a Share extension named Share It listed alongside the built in Twitter Facebook and Flickr share options within the activity view controller Figure 79 2 Share extensions can make use of the SLComposeServiceViewController class to implement the interface for posting content This displays a view Figure 79 3 containing a preview of the information to be posted and provides the ability to modify the content prior to posting it For more complex requirements a custom user interface can be designed using Interface Builder Figure 79 3 The actual mechanics of posting the content will be dependent on the way in which the target platform works 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 Action Extension The Action extension point enables extensions to be created that fall into the Action category Action extensions allow the content within a host app to be transformed or viewed in a different way As with Share extensions Action extensions are accessed from the activity view controller via the Share button Figure 79 4 for example shows an example Action extension named Translator in the activity view controller of the iOS Notes app Figure 79 4 Action extensions are context sensitive in that they only appear as an option when the type of content in the host app matches one of the content types for which the extension has declared support An Action extension that works with images for example will not appear in the activity view controller panel for a host app that is displaying text based content Action extensions are covered in detail in the chapters entitled Creating an iOS 8 Action Extension and Receiving Data from an iOS 8 Action Extension Photo Editing Extension The Photo Editing extension point allows the photo editing capabilities of an application to be accessed from within the built in iOS Photos app Photo Editing extensions are displayed when the user selects an image in the Photos app chooses the edit option and taps on the button in the top left hand corner of the Photo editing screen Figure 79 5 shows the Photos app displaying two Photo Editing extension options Figure 79 5 Photo Editing Extensions are covered in detail in the chapter entitled Creating an

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

  • An iOS 8 Today Extension Widget Tutorial - Techotopia
    9 Enable the Spacing to nearest neighbor constraints on the top and left edges of the label by enabling the red constraint bars and using the current values and with the Constrain to margins option disabled Figure 80 9 Drop down the menu on the Width constraint setting and select the Use current canvas value option Once the spacing and width constraints have been set click on the Add 3 Constraints button to implement the changes Select the bottom Label view and repeat the above steps this time setting spacing constraints on the left top and bottom edges of the view once again using the current spacing values Run the extension and verify that the widget layout appears correctly within the Today view returning to the storyboard file if necessary to make adjustments to the layout Once the layout work is complete display the Assistant Editor panel and make sure that it is showing the source code contained in the TodayViewController swift file Ctrl click on the upper Label view and drag the resulting line to a position beneath the class declaration line in the Assistance Editor panel Release the line and in the resulting connection dialog establish an outlet connection named latitudeLabel Repeat this sequence of steps for the bottom label this time creating an outlet named longitudeLabel Setting the Preferred Content Size in Code Although not necessary in this particular instance since Auto Layout is being used to influence the height of the widget it is worth noting that the height of a widget can be set in code using the setPreferredContentSize method of the extension view controller instance For example the following code changes the height of the widget to 200 before it is displayed to the user override func viewWillAppear animated Bool var currentSize CGSize self preferredContentSize currentSize height 200 0 self preferredContentSize currentSize This technique is particularly useful when it is necessary to dynamically change the size of a widget at runtime A widget might for example display some initial information to the user and provide a More button to display more detailed information In this scenario the More button would simply change the preferred content size to make additional views visible 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 Modifying the Widget View Controller The view controller class for the Today extension widget now needs to be implemented such that it obtains the user s current location and updates the labels in the widget accordingly Select and edit the TodayViewController swift file to import the CoreLocation Framework declare an optional variable in which to store the current location and to create and initialize a location manager instance Note also that the TodayViewController class declaration has been modified to indicate that it now implements the CLLocationManagerDelegate protocol import UIKit import NotificationCenter import CoreLocation

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

  • Creating an iOS 8 Photo Editing Extension - Techotopia
    the view with the Constrain to margins option still switched off Before adding the constraints also enable the Height constraint option using the currently displayed value Display the Assistant Editor and verify that it is displaying the source code for the PhotoEditingViewController swift file Select the Bar Button Item displaying the Sepia text note that it may be necessary to click twice since the first click will select the parent Toolbar view With the item selected Ctrl click on the item and drag the resulting line to a position immediately beneath the end of the implementation of the viewDidLoad method in the Assistant Editor panel Release the line and in the connection dialog establish an Action named sepiaSelected Repeat these steps for the Mono and Invert Bar Button Items naming the Actions monoSelected and invertSelected respectively Finally Ctrl click on the Image View and drag the resulting line to a position beneath the class PhotoEditingViewController declaration Release the line and establish an Outlet for the Image View named imageView The PHContentEditingController Protocol When Xcode created the template for the Photo Editing extension it created a View Controller class named PhotoEditingViewController and declared it as implementing the PHContentEditingController protocol It also generated stub methods for each of the methods that must be implemented in order for the class to conform with the protocol The remainder of implementing a Photo Editing extension primarily consists of writing the code for these methods to implement the required editing behavior One of the first methods that will need to be implemented relates to the issue of adjustment data Photo Extensions and Adjustment Data When a Photo Extension is selected by the user a method named canHandleAdjustmentData is called on the view controller class of the extension The method must return a true or false value depending on whether or not the extension supports adjustment data If an extension supports adjustment data it is passed a copy of the original image or video together with a set of data outlining any earlier modifications made to the media during previous editing sessions The extension then re applies those changes to the file or video to get it back to the point where it was at the end of the last editing session The advantage of this approach is that the extension is able to offer the user the ability to undo any previous editing operations performed within previous sessions using the extension When editing is completed the extension returns the modified image or video file together with any new adjustment data reflecting edits that were performed during the current session If an image editing extension indicates that it does not support adjustment data it is passed a copy of the modified image as it appeared at the end of the last editing session This enables the user to perform additional editing tasks but does not allow previous edits to be undone In the case of video editing extensions that do not support adjustment data the extension will be passed the original video and previous edits will be lost Clearly therefore supporting adjustment data is an important requirement for video editing Whilst the example contained within this tutorial will store and return adjustment data to the Photos app allowing for future improvements to the extension it will not handle incoming adjustment data Within the PhotoEditingViewController swift file therefore locate and review the canHandleAdjustmentData method and verify that it is configured to return a false value func canHandleAdjustmentData adjustmentData PHAdjustmentData Bool return false Receiving the Content The next method that will be called on the extension View Controller class is startContentEditingWithInput This method is passed as arguments a PHContentEditingInput object and a placeholder image For images this object contains a compressed version of the image suitable for displaying to the user a URL referencing the location of the full size image information about the orientation of the image and in the case of extensions with adjustment data support a set of adjustment data from previous edits As previously discussed image extensions with adjustment data support implemented are passed the original image and a set of adjustments to be made to reach parity with the latest state of editing Since it can take time to render these changes the placeholder argument contains a snapshot of the image as it currently appears This can be displayed to the user while the adjustment data is applied and the image rendered in the background For this example the startContentEditingWithInput method will be implemented as follows import UIKit import Photos import PhotosUI class PhotoEditingViewController UIViewController PHContentEditingController IBOutlet weak var imageView UIImageView var input PHContentEditingInput var displayedImage UIImage var imageOrientation Int32 func startContentEditingWithInput contentEditingInput PHContentEditingInput placeholderImage UIImage input contentEditingInput if input nil displayedImage input displaySizeImage imageOrientation input fullSizeImageOrientation imageView image displayedImage The above changes declare two optional variables to contain a reference to the display sized image and the image orientation The code in the method then assigns the display sized image from the PHContentEditingInput object passed to the method to the displayedImage variable and also stores the orientation setting in the imageOrientation variable Finally the display sized image is displayed on the Image View in the user interface so that it is visible to the user Compile and run the extension selecting the Photos app as the host application and verify that the extension displays a copy of the image in the Image View of the extension View Controller 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 Filter Actions The actions connected to the Bar Button Items will change the image by applying Core Image sepia monochrome and invert filters Until the user commits the edits made in the extension any filtering will be performed only on the display sized image to avoid the rendering delays that are likely to

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

  • Creating an iOS 8 Action Extension - Techotopia
    storyboard file Locate this file in the project navigator panel and load it into Interface Builder By default Xcode has created a template user interface consisting of a toolbar a Done button and an image view The only change necessary for the purposes of this example is to replace the image view with a text view Select the image view in the storyboard canvas and remove it using the keyboard delete key From the Object Library panel drag and drop a Text View object onto the storyboard and position and resize it so that it fills the space previously occupied by the image view With the new Text View object still selected display the Resolve Auto Layout Issues menu indicated in Figure 82 6 and select the Reset to Suggested Constraints menu option Figure 82 6 Display the Attributes Inspector for the Text View object and delete the default Latin text and in the Behavior section of the panel turn off the Editable option As previously outlined one of the features of this extension is that the content is displayed in a larger font so take this opportunity to increase the font setting in the Attribute Inspector from System 14 0 to System 39 0 Finally display the Assistant Editor panel and establish an outlet connection for the Text View object named myTextView Remaining within the Assistant Editor delete the line of code declaring the imageView outlet With these changes made the user interface for the Action extension view controller should resemble that of Figure 82 7 Figure 82 7 Receiving the Content The next step in the tutorial is to add some code to receive the content from a host app when the extension is launched All extension view controllers have an associated extension context in the form of an instance of the NSExtensionContext class A reference to the extension context can be accessed via the extensionContext property of the view controller The extension context includes a property named inputItems in the form of an array containing objects which provide access to the content from the host app The input items are in turn contained within one or more NSExtensionItem objects Within the ActionViewController swift file locate the viewDidLoad method remove the template code added by Xcode and modify the method to obtain a reference to the first input item object override func viewDidLoad super viewDidLoad let textItem self extensionContext inputItems 0 as NSExtensionItem Each NSExtensionItem object contains an array of attachment objects These attachment objects are of type NSItemProvider and provide access to the data held by the host app Once a reference to an attachment has been obtained the hasItemConformingToTypeIdentifier method of the object can be called to verify that the host application has data of the type supported by the extension In the case of this example the extension supports text based content so the kUTTypeText uniform type identifier UTI is used to perform this test override func viewDidLoad super viewDidLoad let textItem self extensionContext inputItems

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



  •