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 Overview of iOS 5 iPhone Multitasking - Techotopia
    to the background state either by design or by necessity then the applicationDidEnterBackground delegate method is triggered When a foreground application enters the background the application transitions to the inactive state triggering a call to the application delegate s applicationWillResignActive method This in turn is followed by a transition to background status which is accompanied by a call to the applicationDidEnterBackground method If the application has not indicated that it is eligible to continue running in the background the application is given 5 seconds to complete any tasks before returning from the applicationDidEnterBackground method If these tasks cannot be performed in the time given they may be performed by making a call to the beginBackgroundTaskWithExpirationHandler method followed by a call to the endBackgroundTask method when the task is complete Failure to return from the applicationDidEnterBackground method within the allocated time will result in the application being terminated When an application is moved from the background to the foreground the applicationWill EnterForeground method is triggered followed by a call to applicationDidBecomeActive Finally when an application is about to be terminated either by the user or the system the application delegate s applicationWillTerminate method is called Disabling Multitasking for an iOS Application Multitasking support is the default for all applications developed in Xcode using the iOS 4 0 SDK or later In situations where an application is required to exit rather than enter background mode a configuration setting is required in the application s Info plist file To achieve this load the project associated with the app into Xcode and select the Info plist file from the Supporting Files section of the project navigator panel In order to disable multitasking the Application does not run in background key must be added to the file with the value of YES If this key is not already listed in the file select the bottom most item in the list and click on the button to add a new key At this point a drop down menu will appear containing a list of available keys Scroll down the list to locate and select the Application does not run in background key as illustrated in Figure 44 1 Figure 44 1 Once selected set the value located in the Value column to YES Figure 44 2 Checking for Multitasking Support Multitasking is only supported on the iPhone 3GS and later devices running iOS 4 0 or newer In the case of devices where multitasking is not supported applications are simply terminated rather than being placed in the background If you are developing an application that relies on multitasking it is recommended that defensive code be implemented to check for multitasking support so that application behavior can be modified to compensate for the missing functionality This can be achieved using the following code fragment bool multitaskingAvailable UIDevice device UIDevice currentDevice backgroundIsSupported NO if device respondsToSelector selector isMultitaskingSupported backgroundISSupported device multitaskingSupported return backgroundIsSupported When the above method is called it returns either YES or NO depending on whether

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


  • Scheduling iOS 5 iPhone Local Notifications - Techotopia
    notification must be placed In the case of this example a template method can be found in the localNotifyAppDelegate m file Within the main Xcode project navigator panel select this file and scroll down until the method comes into view void applicationDidEnterBackground UIApplication application Use this method to release shared resources save user data invalidate timers and store enough application state information to restore your application to its current state in case it is terminated later If your application supports background execution called instead of applicationWillTerminate when the user quits Adding a Sound File to the Project When a local notification is triggered the option is available to play a sound to gain the user s attention If such an audio alert is required the corresponding sound file must be added to the application project resources and must be in Linear PCM MA4 IMA ADPCM uLaw or aLaw format If no sound file is specified the default is for the notification to be silent though the iPhone device will still vibrate For the purposes of this exercise we will copy an audio file from the Mac OS X system on which Xcode is running and use it when scheduling the notification To locate this file open the Finder tool and search for a file named Glass aiff AIFF being PCM format Once located drag this file and drop it onto the Supporting Files category located in the Xcode project navigator panel and click the Finish button in the resulting panel The audio file should now be included in the list of resources for the project ready to be accessed by the application code Scheduling the Local Notification Local notifications require the use of the UILocalNotification class combined with an NSDate object configured with the date and time that the notification is to be triggered Properties may also be set to specify the text to be displayed to the user an optional repeat interval and a message to be displayed to the user in the alert box With these requirements in the mind the following code creates an NSDate object based on the current date and time plus 10 seconds This date object is then used to schedule a notification with no repeats a text message and the sound from the Glass aiff file void applicationDidEnterBackground UIApplication application NSDate alertTime NSDate date dateByAddingTimeInterval 10 UIApplication app UIApplication sharedApplication UILocalNotification notifyAlarm UILocalNotification alloc init if notifyAlarm notifyAlarm fireDate alertTime notifyAlarm timeZone NSTimeZone defaultTimeZone notifyAlarm repeatInterval 0 notifyAlarm soundName Glass aiff notifyAlarm alertBody Staff meeting in 30 minutes app scheduleLocalNotification notifyAlarm Testing the Application To test the application click on the Run tool bar button located in the Xcode project window After compiling and linking the application it will load and run in the iOS Simulator Once the application has loaded into the iPhone simulator click on the device home button to place the app into background mode After 10 seconds have elapsed the notification should appear accompanied by the glass sound from

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

  • Getting iPhone Location Information using the iOS 5 Core Location Framework - Techotopia
    locationMgr CLLocationManager alloc init locationMgr desiredAccuracy kCLLocationAccuracyBest locationMgr delegate self locationMgr startUpdatingLocation With each location update an application delegate method named didUpdateToLocation is called by the location manager and passed information about the current location The above code also therefore assigns the current class as the location manager s delegate Configuring the Desired Location Accuracy The level of accuracy to which location information is to be tracked is specified via the desiredAccuracy property of the CLLocationManager object It is important to keep in mind when configuring this property that the greater the level of accuracy selected the greater the drain on the device battery An application should therefore never request a greater level of accuracy than is actually needed A number of predefined constant values are available for use when configuring this property kCLLocationAccuracyBestForNavigation Uses the highest possible level of accuracy augmented by additional sensor data This accuracy level is intended solely for use when the device is connected to an external power supply kCLLocationAccuracyBest The highest recommended level of accuracy for devices running on battery power kCLLocationAccuracyNearestTenMeters Accurate to within 10 meters kCLLocationAccuracyHundredMeters Accurate to within 100 meters kCLLocationAccuracyKilometer Accurate to within one kilometer kCLLocationAccuracyThreeKilometers Accurate to within three kilometers Configuring the Distance Filter The default configuration for the location manager is to report updates whenever any changes are detected in the location of the device The distanceFilter property of the location manager allows applications to specify the amount of distance the device location must change before an update is triggered If for example the distance filter is set to 1000 meters the application will only receive a location update when the device travels 1000 meters or more from the location of the last update For example to specify a distance filter of 1500 meters locationMgr distanceFilter 1500 0f The distance filter may be cancelled thereby returning to the default setting using the kCLDistanceFilterNone constant locationMgr distanceFilter kCLDistanceFilterNone The Location Manager Delegate Location manager updates and errors result in calls to two delegate methods defined within the CLLocationManagerDelegate protocol Templates for the two delegate methods that must be implemented to comply with this protocol are as follows pragma mark pragma mark CLLocationManagerDelegate void locationManager CLLocationManager manager didUpdateToLocation CLLocation newLocation fromLocation CLLocation oldLocation Handle location updates void locationManager CLLocationManager manager didFailWithError NSError error Handle error Obtaining Location Information from CLLocation Objects Location information is passed through to the didUpdateLocation delegate method in the form of CLLocation objects A CLLocation object encapsulates the following data Latitude Longitude Horizontal Accuracy Altitude Altitude Accuracy Longitude and Latitude Longitude and latitude values are stored as type CLLocationDegrees and may be obtained from a CLLocation object as follows CLLocationDegrees currentLatitude location coordinate latitude CLLocationDegrees currentLongitude location coordinates longitude Accuracy Horizontal and vertical accuracy are stored in meters as CLLocationDistance values and may be accessed as follows CLLocation verticalAccuracy location verticalAccuracy CLLocation horizontalAccurcy location horizontalAccuracy Altitude The altitude value is stored in meters as a type CLLocationDistance value and may be accessed from a CLLocation object

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

  • An Example iOS 5 iPhone Location Application - Techotopia
    accuracy data make sure that the labels are stretched to the right until the blue margin guideline appears The data will be displayed to multiple levels of decimal points requiring space beyond the default size of the label Establish a connection between the latitude outlet declared in the view controller and the corresponding user interface label by Ctrl clicking on the File s Owner icon and dragging the blue line to the label located to the right of the Latitude label Release the line and select the latitude outlet from the resulting menu Repeat this task to establish outlet connections to the remaining six data display labels The final step of the user interface design process is to connect the button object to the resetDistance action method This is achieved by selecting the button in the view window and displaying the Connections Inspector window View Utilities Show Connections Inspector Click in the round circle to the right of the Touch Up Inside event and drag the line to the File s Owner object On releasing the mouse button select the resetDistance method from the resulting menu Creating the CLLocationManager Object The next task is to implement the code to create an instance of the CLLocationManager class Since this needs to occur when the application starts up an ideal location is in the view controller s viewDidLoad method Whilst making this code change it is also a good opportunity to add the necessary synthesize directives to the locationViewController m file import locationViewController h implementation locationViewController synthesize longitude latitude horizontalAccuracy verticalAccuracy altitude distance synthesize locationManager startLocation void viewDidLoad super viewDidLoad self locationManager CLLocationManager alloc init locationManager desiredAccuracy kCLLocationAccuracyBest locationManager delegate self locationManager startUpdatingLocation startLocation nil The above code creates a new CLLocationManager object instance and configures it to use the best accuracy setting It then declares itself as the application delegate for the object The location manager object is then instructed to begin updating location information via a call to the startUpdatingLocation method Since location tracking has just begun at this point the startLocation object is also set to nil 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 object to nil void resetDistance 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 pragma mark pragma mark CLLocationManagerDelegate void locationManager CLLocationManager manager didUpdateToLocation CLLocation newLocation fromLocation CLLocation oldLocation NSString currentLatitude NSString alloc initWithFormat g newLocation coordinate latitude latitude text currentLatitude NSString currentLongitude NSString alloc initWithFormat g newLocation coordinate longitude longitude text currentLongitude NSString currentHorizontalAccuracy NSString alloc initWithFormat g newLocation horizontalAccuracy horizontalAccuracy text currentHorizontalAccuracy NSString currentAltitude NSString alloc initWithFormat g newLocation altitude altitude text currentAltitude NSString currentVerticalAccuracy NSString

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

  • Working with Maps on the iPhone with MapKit and the MKMapView Class - Techotopia
    and to add a toolbar instance to the user interface Begin by selecting the mapSampleViewController xib file so that the Interface Builder panel appears Drag a Tool Bar from the Object Library and place it at the bottom of the view canvas Next drag and drop a Map View object onto the canvas and resize and position it so that it takes up the remaining space in the view above the toolbar google ADSDAQBOX FLOW google Figure 48 1 If present select the button in the toolbar labeled Item and press the Delete key on the keyboard to remove it from the design Connect the mapView outlet to the object by Ctrl clicking on the File s Owner object and dragging the resulting line to the Map View object Release the line and select mapView from the menu Repeat these steps to map the toolbar outlet to the tool bar object 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 48 2 Figure 48 2 Adding the Tool Bar Items Next the two buttons need to be added to the navigation bar This code will be placed in the viewDidLoad method located in the mapSampleViewController m file Now is also a good time to configure the mapView to display the user s current location by setting the showsUserLocation property void viewDidLoad super viewDidLoad mapView showsUserLocation YES UIBarButtonItem zoomButton UIBarButtonItem alloc initWithTitle Zoom style UIBarButtonItemStylePlain target self action selector zoomIn UIBarButtonItem typeButton UIBarButtonItem alloc initWithTitle Type style UIBarButtonItemStylePlain target self action selector changeMapType NSArray buttons NSArray alloc initWithObjects zoomButton typeButton nil toolBar items buttons First the mapView is configured to show the user location which appears on the map as a blue translucent ball mapView showsUserLocation YES Next two tool bar button items labeled Zoom and Type are created and configured to call the zoomIn and changeMapType methods respectively These button are then placed in an array and the array assigned to the items property of the toolbar object in order to make them visible to the user Changing the MapView Region When the Zoom button is tapped by the user the map view region needs to be changed so that the user s current location is set as the center location and the region span needs to be changed to 50 meters analogous to zooming in to the map region The code to implement this belongs in the zoomIn method located in the mapSampleViewController m file void zoomIn id sender MKUserLocation userLocation mapView userLocation MKCoordinateRegion region MKCoordinateRegionMakeWithDistance userLocation location coordinate 50 50 mapView setRegion region animated NO This method performs some very simple operations in order to achieve the desired effect in the mapView object Firstly the user s current location is ascertained by accessing the userLocation property of the map view object This is stored in the form of an MKUserLocation object which in turn

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

  • Accessing the iOS 5 iPhone Camera and Photo Library - Techotopia
    this property Whether or not the user is permitted to perform editing before the image 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 movie and image support and editing allowed It then displays the controller and releases the controller object UIImagePickerController imagePicker UIImagePickerController alloc init imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceTypeCamera imagePicker mediaTypes NSArray arrayWithObjects NSString kUTTypeImage NSString kUTTypeMovie nil imagePicker allowsEditing YES self presentModalViewController imagePicker animated YES 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 void imagePickerController UIImagePickerController picker didFinishPickingMediaWithInfo NSDictionary info Code here to work with media self dismissModalViewControllerAnimated YES void imagePickerControllerDidCancel UIImagePickerController picker self dismissModalViewControllerAnimated YES 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 NSString mediaType info objectForKey UIImagePickerControllerMediaType if mediaType isEqualToString NSString kUTTypeImage Media is an image else if mediaType isEqualToString NSString kUTTypeMovie Media is a video The original unedited image selected or photographed by the user may be obtained from the info dictionary as follows UIImage image info objectForKey UIImagePickerControllerOriginalImage Assuming that editing was enabled on the image picker controller object the edited version of image may be accessed via the UImagePickerControllerEditedImage dictionary key UIImage image info objectForKey UIImagePickerControllerEditedImage If the media is a video the URL of the recorded media may be accessed as follows NSURL url info objectForKey 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 MPMoviePlayer class as outlined the chapter entitled Video Playback from within an iOS 5 iPhone Application Detecting Device Capabilities Not all iOS devices provide the same functionality iPhone models prior to the 3GS model for example do not support the

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

  • An Example iOS 5 iPhone Camera Application - Techotopia
    modify it is follows import UIKit UIKit h import MobileCoreServices MobileCoreServices h interface cameraViewController UIViewController UIImagePickerControllerDelegate UINavigationControllerDelegate UIImageView imageView BOOL newMedia property strong nonatomic IBOutlet UIImageView imageView IBAction useCamera IBAction useCameraRoll end Designing the User Interface The next step in this tutorial is to design the user interface This is a very simple user interface consisting of an image view and two buttons Select the cameraViewContoller xib file and drag and drop components from the Library window View Utilities Show Object Library onto the view Position and size the components and set the text on the button so that the user interface resembles Figure 50 1 Next Ctrl click on the File s Owner object and drag the resulting line to the UIImageView object in the view window Select the imageView outlet from the resulting menu Select the Camera button and display the Connections Inspector panel View Utilities Connections Inspector Click inside the circle to the right of the Touch Up Inside event and drag the line to the File s Owner object Select the useCamera method from the resulting menu Repeat these steps to connect the Camera Roll button to the useCameraRoll action method Figure 50 1 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 and the UIImagePickerController object released The last task is to set the newMedia flag to YES to indicate that the image is new and is not an existing image from the camera roll Bringing all these requirements together along with the synthesize directive gives us the following useCamera method import cameraViewController h implementation cameraViewController synthesize imageView void useCamera if UIImagePickerController isSourceTypeAvailable UIImagePickerControllerSourceTypeCamera UIImagePickerController imagePicker UIImagePickerController alloc init imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceTypeCamera imagePicker mediaTypes NSArray arrayWithObjects NSString kUTTypeImage nil imagePicker allowsEditing NO self presentModalViewController imagePicker animated YES newMedia YES end The useCameraRoll method is remarkably similar to the previous method with the exception that the source of the image is declared to be UIImagePickerControllerSourceTypePhotoLibrary and the newMedia flag is set to NO since the photo is already in the library we don t need to save it again void useCameraRoll if UIImagePickerController isSourceTypeAvailable UIImagePickerControllerSourceTypeSavedPhotosAlbum UIImagePickerController imagePicker UIImagePickerController alloc init imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceTypePhotoLibrary imagePicker mediaTypes NSArray arrayWithObjects NSString kUTTypeImage nil imagePicker allowsEditing NO self presentModalViewController imagePicker animated YES newMedia NO Writing the Delegate Methods As described in Accessing the iPhone Camera and Photo Library in order to fully implement an instance of the image picker controller delegate protocol it is necessary to implement some delegate methods The most important method is didFinishPickingMediaWithInfo which is called

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

  • Video Playback from within an iOS 5 iPhone Application - Techotopia
    from the project navigator panel the top item named movie and clicking on the Build Phases tab in the main panel In the Link Binary with Libraries section click on the button select the MediaPlayer framework entry from the resulting panel and click on the Add button Declaring the Action Method and MoviePlayer Instance The application user interface is going to consist of a single button which when pressed will initiate the movie playback process We therefore need to declare an action method called playMovie in our movieViewController h file It is also imperative that the MediaPlayer MediaPlayer h file be imported to avoid a catalog of unresolved references when the application is compiled and also add a reference to an instance of the MPMoviePlayerController class import UIKit UIKit h import MediaPlayer MediaPlayer h interface movieViewController UIViewController MPMoviePlayerController moviePlayer property strong nonatomic MPMoviePlayerController moviePlayer IBAction playMovie end Select the movieViewController m and add the synthesize directive for the moviePlayer import movieViewController h implementation movieViewController synthesize moviePlayer end Designing the User Interface Select the movieViewController xib file and display the Object library View Utilities Object Library Drag a single UIButton instance to the view window and change the text on the button to Play Movie With the button selected display the connections inspector window View Utilities Show Connections Inspector click on the circle to the right of the Touch Up Inside event and drag the blue line to the File s Owner object From the resulting menu select the playMove action method Adding the Video File to the Project Resources Initially the video file to be displayed to the user is going to be bundled on the device with the application In a later section we will look at streaming a movie from a remote network location Begin by finding a suitable movie file for inclusion in the application Any movie recorded by an iPhone will suffice for this purpose Copy the movie file to the system on which Xcode is running and name it movie mov Locate the file in a Finder window and drag and drop it onto the Supporting Files folder in the project navigator panel Implementing the Action Method The next step is to write the code for the action method so that video playback is initiated when the button is touched by the user The code for the method should be placed in the movieViewController m file as follows void playMovie NSURL url NSURL fileURLWithPath NSBundle mainBundle pathForResource MOVIE ofType MOV moviePlayer MPMoviePlayerController alloc initWithContentURL url NSNotificationCenter defaultCenter addObserver self selector selector moviePlayBackDidFinish name MPMoviePlayerPlaybackDidFinishNotification object moviePlayer moviePlayer controlStyle MPMovieControlStyleDefault moviePlayer shouldAutoplay YES self view addSubview moviePlayer view moviePlayer setFullscreen YES animated YES The above method constructs an NSURL object based on the video file that was added to the project resources This is then used in the creation of a new instance of the MPMoviePlayerController class A notification is then configured such that the moviePlaybackDidFinish method is called when the playback finishes Next properties are

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



  •