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".
  • Receiving Data from an iOS 8 Action Extension - Techotopia
    project will make use of a definition which is declared within the Mobile Core Services framework To avoid compilation errors this framework must be imported into the ViewController swift file as follows import UIKit import MobileCoreServices class ViewController UIViewController Adding a Share Button to the Application In order to be able to access the Change it Up Action extension from within this host application it will be necessary to implement a Share button As the user interface currently stands the toolbar contains a single button item displaying text which reads Item To change this to a Share button select it in the storyboard layout keeping in mind that it may be necessary to click on it twice since the first click typically selects the parent toolbar rather than the button item With the button selected display the Attributes Inspector and change the Identifier menu from Custom to Action Figure 83 2 Once the change has been made the button item should now have the standard appearance of an iOS Share button as shown in Figure 83 3 Figure 83 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 Now that the button looks like a Share button some code now needs to be added to display the activity view controller when it is tapped by the user With the Assistant Editor displayed Ctrl click on the button and drag the resulting line to a suitable location within the ViewController swift file Release the line and create an Action outlet named showActionView Once created implement the code in this method so that it reads as follows IBAction func showActionView sender AnyObject let activityViewController UIActivityViewController activityItems myTextView text applicationActivities nil self presentViewController activityViewController animated true completion nil activityViewController completionWithItemsHandler myHandler The code within the method creates a new UIActivityViewController instance initialized with the content of the Text View in the user interface The activity view controller is then displayed to the user Finally a method is assigned to act as the completion handler to be called when the Action extension returns control to the application For now this can be implemented as a stub method as follows func myHandler activityType String completed Bool returnedItems AnyObject error NSError Compile and run the application and tap the Share button to test that the activity view controller appears Select the Change it Up extension and verify that it displays the text extracted from the Text View Finally tap the Done button to return to the host app noting that the original text content has not yet been converted to uppercase This functionality now needs to be implemented within the completion handler method Receiving Data from an Extension When the user exits from an Action extension the completion handler assigned to the UIActivityViewController instance will be called and passed a variety of parameters One

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


  • Using iOS 8 Event Kit and Swift to Create Date and Location Based Reminders - Techotopia
    the Main storyboard file it is clear that Xcode has created a template based tabbed application consisting of a Tab Bar Controller and two Views each of which has its own view controller For the purposes of this example the first view will be used to implement a screen whereby the user can create a new date and time based reminder Within the Storyboard canvas therefore locate the First View screen and remove the current labels that were added by Xcode With a clean view add a Text Field Date Picker and Button object to the view canvas Once added position and configure the user interface layout so that it resembles that of Figure 84 3 Figure 84 3 Shift click on all three views so that all of the objects are selected then use the Auto Layout Align menu to position the views in the horizontal center of the container Select the Text Field view and using the Auto Layout Pin menu configure a Spacing to nearest neighbor constraint on the top edge of the view using the current distance value and with the Constrain to margins option switched off Within the Pin panel also enable the Width constraint using the current value before clicking on the Add 2 Constraints button Next select the Button view and add a constraint on the top edge to the nearest neighbor once again with the Constrain to margins option switched off Repeat the above step with the Date Picker view selected this time also enabling the Height and Width constraints Select the Text Field object and display the Assistant Editor using View Assistant Editor Show Assistant Editor menu option making sure that it is displaying the content of the FirstViewController swift file If it is not click on the file name in the bar at the top of the Assistant Editor panel and select the file from the drop down menu Ctrl click on the Text Field object in the view and drag the resulting line to the area immediately beneath the class declaration line in the Assistant Editor panel Upon releasing the line the configuration panel will appear Configure the connection as an Outlet named reminderText and click on the Connect button Repeat this step to add an outlet connection to the Date Picker object named myDatePicker Finally Ctrl click on the Button object drag the line to the Assistant Editor and release it beneath the end of the viewDidLoad method In the resulting connection panel change the connection type to Action and name the action setReminder Implementing the Reminder Code With the user interface view designed the next step is to implement the code in the view controller for the first view to access the event store and set up the reminder We will need a place to store the event store object once it has been requested and as previously discussed it is recommended that access to the event store be requested only once As such we will need a location to store the reference once it has been obtained so select the AppDelegate swift file import the EventKit Framework and declare a variable in which to save the event store reference import UIKit import EventKit UIApplicationMain class AppDelegate UIResponder UIApplicationDelegate var window UIWindow var eventStore EKEventStore Next edit the FirstViewController swift file import the EventKit Framework and add a variable in which to store a reference to the application delegate import UIKit import EventKit class FirstViewController UIViewController IBOutlet weak var reminderText UITextField IBOutlet weak var myDatePicker UIDatePicker var appDelegate AppDelegate Locate the setReminder template stub and add the following code IBAction func setReminder sender AnyObject appDelegate UIApplication sharedApplication delegate as AppDelegate if appDelegate eventStore nil appDelegate eventStore EKEventStore appDelegate eventStore requestAccessToEntityType EKEntityTypeReminder completion granted error in if granted println Access to store not granted println error localizedDescription else println Access granted if appDelegate eventStore nil self createReminder 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 code added to the method verifies that access to the event store has not already been obtained and in the event that it has not requests access to the reminder calendars If access is denied a message is reported to the console In the event that access is granted a second method named createReminder is called With FirstViewController swift still in the editing panel implement this method func createReminder let reminder EKReminder eventStore appDelegate eventStore reminder title reminderText text reminder calendar appDelegate eventStore defaultCalendarForNewReminders let date myDatePicker date let alarm EKAlarm absoluteDate date reminder addAlarm alarm var error NSError appDelegate eventStore saveReminder reminder commit true error error if error nil println Reminder failed with error error localizedDescription The createReminder method creates a new EKReminder object associated with the event store and sets the title property to the content of the Text Field object in the user interface The code elects the default calendar as the target for the reminder and then creates an EKAlarm object primed with the date value selected by the user in the Date Picker object The alarm is then added to the reminder which in turn is saved in the event store Errors are output to the console for debugging purposes Hiding the Keyboard Before moving on to the next part of the tutorial some code will now need to be added to the application so that the keyboard is withdrawn when the user touches the view background Within the FirstViewController swift file override the code in the touchesBegan method override func touchesBegan touches Set NSObject withEvent event UIEvent reminderText endEditing true With the time and date based reminder phase of the application completed the next step is to implement the location based reminder functionality Designing the Location based Reminder Screen The tab controller created on our behalf by Xcode contains a second view that will

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

  • Accessing the iOS 8 Camera and Photo Library in Swift - Techotopia
    is passed on to the application is controlled via the allowsEditing Boolean property The following code creates a UImagePickerController instance and configures it for camera use with image support and editing disabled before displaying the controller let imagePicker UIImagePickerController imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceType PhotoLibrary imagePicker mediaTypes kUTTypeImage as NSString imagePicker allowsEditing false self presentViewController imagePicker animated true completion nil It should be noted that the above code also configured the current class as the delegate for the UIImagePickerController instance This is actually a key part of how the class works and is covered in the next section Configuring the UIImagePickerController Delegate When the user is presented with the UIImagePickerController object user interface the application essentially hands control to that object That being the case the controller needs some way to notify the application that the user has taken a photo recorded a video or made a library selection It does this by calling delegate methods The class that instantiates a UIImagePickerController instance should therefore declare itself as the object s delegate conform to the UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols and implement the didFinishPickingMediaWithInfo and imagePickerControllerDidCancel methods When the user has selected or created media the didFinishPickingMediaWithInfo method is called and passed an NSDictionary object containing the media and associated data In the event that the user cancels the operation the imagePickerControllerDidCancel method is called In both cases it is the responsibility of the delegate method to dismiss the view controller func imagePickerController picker UIImagePickerController didFinishPickingMediaWithInfo info NSObject AnyObject Code here to work with media self dismissViewControllerAnimated true completion nil func imagePickerControllerDidCancel picker UIImagePickerController self dismissViewControllerAnimated true completion nil 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 info argument passed to the didFinishPickingMediaWithInfo method is an NSDictionary object containing the data relating to the image or video created or selected by the user The first step is typically to identify the type of media let mediaType info UIImagePickerControllerMediaType as NSString if mediaType isEqualToString kUTTypeImage as String Media is an image else if mediaType isEqualToString kUTTypeMovie as String Media is a video The original unedited image selected or photographed by the user may be obtained from the info dictionary as follows let image info UIImagePickerControllerOriginalImage as UIImage Assuming that editing was enabled on the image picker controller object the edited version of the image may be accessed via the UImagePickerControllerEditedImage dictionary key let image info UIImagePickerControllerEditedImage as UIImage If the media is a video the URL of the recorded media may be accessed as follows let url info UIImagePickerControllerMediaURL Once the image or video URL has been obtained the application can optionally save the media to the library and either display the image to the user or play the video using the AVPlayer and AVPlayerViewController classes as outlined in the chapter entitled iOS 8 Video Playback using AVPlayer

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

  • An Example Swift iOS 8 iPhone Camera Application - Techotopia
    of the view this time with the Constrain to margins option enabled Finally with the Image View still selected display the Attributes Inspector panel and change the Mode attribute to Aspect Fit Select the image view object in the view canvas display the Assistant Editor panel Ctrl click on the image 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 imageView With the Assistant Editor still visible establish action connections for the two buttons to methods named useCamera and useCameraRoll respectively keeping mind that it may be necessary to click twice on each button to select it since the first click will typically select the toolbar parent object Close the Assistant Editor select the ViewController swift file and modify it further to add import and delegate protocol declarations together with a Boolean property declaration that will be required later in the chapter import UIKit import MobileCoreServices class ViewController UIViewController UIImagePickerControllerDelegate UINavigationControllerDelegate IBOutlet weak var imageView UIImageView var newMedia Bool Implementing the Action Methods The useCamera and useCameraRoll action methods now need to be implemented The useCamera method first needs to check that the device on which the application is running has a camera It then needs to create a UIImagePickerController instance assign the cameraViewController as the delegate for the object and define the media source as the camera Since we do not plan on handling videos the supported media types property is set to images only Finally the camera interface will be displayed The last task is to set the newMedia flag to true to indicate that the image is new and is not an existing image from the camera roll Bringing all these requirements together gives us the following useCamera method IBAction func useCamera sender AnyObject if UIImagePickerController isSourceTypeAvailable UIImagePickerControllerSourceType Camera let imagePicker UIImagePickerController imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceType Camera imagePicker mediaTypes kUTTypeImage as NSString imagePicker allowsEditing false self presentViewController imagePicker animated true completion nil newMedia true 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 useCameraRoll method is remarkably similar to the previous method with the exception that the source of the image is declared to be UIImagePickerControllerSourceType PhotoLibrary and the newMedia flag is set to false since the photo is already in the library we don t need to save it again IBAction func useCameraRoll sender AnyObject if UIImagePickerController isSourceTypeAvailable UIImagePickerControllerSourceType SavedPhotosAlbum let imagePicker UIImagePickerController imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceType PhotoLibrary imagePicker mediaTypes kUTTypeImage as NSString imagePicker allowsEditing false self presentViewController imagePicker animated true completion nil newMedia false Writing the Delegate Methods As described in Accessing the iOS 8 Camera and Photo Library in Swift in order to fully implement an instance of the image picker controller delegate protocol it is

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

  • IOS 8 Video Playback using AVPlayer and AVPlayerViewController - Techotopia
    template configured for the Swift language and Universal devices naming the product AVPlayerDemo Adding the AVKit Framework to the Xcode Project Once the new project has been created the first step is to make sure the AVKit Framework is included in the project Failure to add this framework will result in the application crashing at runtime To add the AVKit framework select the AVPlayerDemo target located at the top of the project navigator panel In the center pane select the Build Phases tab and unfold the Link Binary With Libraries panel Click on the button to display a list of existing frameworks locate and select AVKit framework and click the Add button The AVKit framework will now appear in the frameworks list along with any other frameworks already included in the project Designing the User Interface Select the Main storyboard file and display the Object Library View Utilities Show Object Library Drag a single Button instance to the view window and change the text on the button to Play Movie With the button selected in the storyboard canvas display the Auto Layout Align menu and add both horizontal and vertical Center in Container constraints to the view From the Object Library panel locate the AVKit Player View Controller object and drag and drop it onto the storyboard to the right of the existing view controller Ctrl click on the button in the first view controller and drag the resulting line to the second AVKit Player View Controller Release the line and select show from the segue selection menu On completion of these tasks the storyboard should resemble that of Figure 87 1 Figure 87 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 Initializing Video Playback When the Play Movie button is tapped by the user the application will perform a segue to the AVPlayerViewController scene Verify that this works by running the application and selecting the button The AVPlayerViewController will appear and display the video playback controls but as yet no AVPlayer has been configured to play video content This can be achieved by implementing the prepareForSegue method within the ViewController swift file as follows the code for which relies on the AVKit and AVFoundation frameworks having been imported import UIKit import AVKit import AVFoundation class ViewController UIViewController override func prepareForSegue segue UIStoryboardSegue sender AnyObject let destination segue destinationViewController as AVPlayerViewController let url NSURL string http www ebookfrenzy com ios book movie movie mov destination player AVPlayer URL url The code in this above method begins by obtaining a reference to the destination view controller in this case the AVPlayerViewController instance An NSURL object is then initialized with the URL of a web based video file Finally a new AVPlayer instance is created initialized with the video URL and assigned to the player property of the AVPlayerViewController

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

  • Playing Audio on iOS 8 using AVAudioPlayer - Techotopia
    a new Universal Single View Application named AudioDemo using the Swift programming language Adding an Audio File to the Project Resources In order to experience audio playback it will be necessary to add an audio file to the project resources For this purpose any supported audio format file will be suitable Having identified a suitable audio file drag and drop it into the Supporting Files folder of the project navigator panel of the main Xcode window For the purposes of this tutorial we will be using an MP3 file named Moderato mp3 which can be found in the audiofiles folder of the sample code archive downloadable from the following URL http www ebookfrenzy com web ios8 Having downloaded and unzipped the file locate it in a Finder window and drag and drop it onto the Supporting Files section of the Xcode project navigator panel 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 Designing the User Interface The application user interface is going to comprise two buttons labeled Play and Stop and a slider to allow the volume of playback to be adjusted Select the Main storyboard file display the Object Library View Utilities Show Object Library drag and drop components from the Library onto the View window and modify properties so that the interface appears as illustrated in Figure 88 1 Figure 88 1 With the scene view selected within the storyboard canvas display the Auto Layout Resolve Auto Layout Issues menu and select the Reset to Suggested Constraints menu option listed in the All Views in View Controller section of the menu Select the slider 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 slider 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 volumeControl Ctrl click on the Play 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 playAudio Repeat these steps to establish an action on the Stop button to a method named stopAudio Ctrl click on the slider object and drag the line to the area immediately beneath the newly created actions in the Assistant Editor panel Release the line and within the resulting connection dialog establish an Action method on the Value Changed event configured to call a method named adjustVolume Close the Assistant Editor panel and select the ViewController swift file in the project navigator panel and add an import directive and delegate declaration together with a

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

  • Recording Audio on iOS 8 with AVAudioRecorder in Swift - Techotopia
    verify that the editor is displaying the contents of the ViewController swift file Ctrl click on the Record button 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 recordButton Repeat these steps to establish outlet connections for the Play and Stop buttons named playButton and stopButton respectively Continuing to use the Assistant Editor establish Action connections from the three buttons to methods named recordAudio playAudio and stopAudio Close the Assistant Editor panel select the ViewController swift file and modify it to import the AVFoundation framework declare adherence to some delegate protocols and to add properties to store references to AVAudioRecorder and AVAudioPlayer instances import UIKit import AVFoundation class ViewController UIViewController AVAudioPlayerDelegate AVAudioRecorderDelegate var audioPlayer AVAudioPlayer var audioRecorder AVAudioRecorder 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 the AVAudioRecorder Instance When the application is first launched an instance of the AVAudioRecorder class needs to be created This will be initialized with the URL of a file into which the recorded audio is to be saved Also passed as an argument to the initialization method is an NSDictionary object indicating the settings for the recording such as bit rate sample rate and audio quality A full description of the settings available may be found in the appropriate Apple iOS reference materials As is often the case a good location to initialize the AVAudioRecorder instance is the viewDidLoad method of the view controller located in the ViewController swift file Select the file in the project navigator locate this method and modify it so that it reads as follows override func viewDidLoad super viewDidLoad playButton enabled false stopButton enabled false let dirPaths NSSearchPathForDirectoriesInDomains DocumentDirectory UserDomainMask true let docsDir dirPaths 0 as String let soundFilePath docsDir stringByAppendingPathComponent sound caf let soundFileURL NSURL fileURLWithPath soundFilePath let recordSettings AVEncoderAudioQualityKey AVAudioQuality Min rawValue AVEncoderBitRateKey 16 AVNumberOfChannelsKey 2 AVSampleRateKey 44100 0 var error NSError let audioSession AVAudioSession sharedInstance audioSession setCategory AVAudioSessionCategoryPlayAndRecord error error if let err error println audioSession error err localizedDescription audioRecorder AVAudioRecorder URL soundFileURL settings recordSettings as NSObject AnyObject error error if let err error println audioSession error err localizedDescription else audioRecorder prepareToRecord Since no audio has yet been recorded the above method disables the play and stop buttons It then identifies the application s documents directory and constructs a URL to a file in that location named sound caf An NSDictionary object is then created containing the recording quality settings before an audio session and an instance of the AVAudioRecorder class are created Assuming no errors are encountered the audioRecorder instance is prepared to begin recording when requested to do so by the user Implementing the Action Methods The next step is to implement the action methods connected to the three button

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

  • Integrating Twitter and Facebook into iOS 8 Applications using Swift - Techotopia
    application Options are also provided on the Facebook settings panel to control which applications have access to the Facebook account and to modify or delete the currently configured Facebook account When using the SLRequest class to construct API requests it will be necessary to use the Accounts Framework to identify and request permission to use the corresponding social network accounts in an application When using the UIActivityViewController or SLComposeViewController classes however the account handling is performed automatically by the class The remainder of this chapter will focus on the UIActivityViewController and SLComposeViewController classes The SLRequest class will be covered in detail in the chapter entitled iOS 8 Facebook and Twitter Integration using SLRequest and Swift Using the UIActivityViewController Class The UIActivityViewController class is instantiated within an application at the point at which a posting is ready to be made to a social network Once the user takes an action to post an update from within an application the screen shown in Figure 90 2 will appear listing the options that are available Figure 90 2 Once a destination social network has been selected the preview sheet for the chosen service Figure 90 3 shows the sheet for a Facebook posting will appear primed with the content of the update to be sent consisting of text and any optional image attachments Having reviewed and optionally modified the post the user may then send the message Figure 90 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 In the event that the user has not yet configured an account for the selected social network in the Settings application a dialog will appear providing the option to either set up an account or cancel the post The assumption is generally made that at the point an instance of UIActivityViewController is created the application will already have gathered together the text and images that are to be included in the post These items need to be placed into an array object and passed to the controller before it is presented to the user The following code excerpt for example instantiates a UIActivityViewController instance primed with text and an image to be included in the post and presents it to the user let postText Great to finally be here on vacation let postImage UIImage named windsor castle jpg let activityItems postText postImage let activityController UIActivityViewController activityItems activityItems applicationActivities nil self presentViewController activityController animated true completion nil Using the SLComposeViewController Class In order to use the SLComposeViewController class a number of steps should be performed in sequence Firstly the application may optionally check to verify whether a message can be sent to the specified social network service This essentially equates to checking if a valid social network account has been configured on the device and is achieved using the isAvailableForServiceType class method passing through

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



  •