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".
  • Getting iPad Location Information using the iOS 6 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 type a CLLocationDistance value and may be accessed from a CLLocation object

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


  • An Example iOS 6 iPad Location Application - Techotopia
    connecting then to properties named longitude horizontalAccuracy altitude verticalAccuracy and distance respectively The final step of the user interface design process is to connect the button object to an action method Ctrl click on the button object and drag the line to the area immediately beneath the newly created outlets 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 resetDistance Select the LocationViewController h file verify that the outlets are configured correctly and add a property in which to store the start location coordinates and the location manager object Now is also an opportune time to import the CoreLocation CoreLocation h header file and to declare the class as implementing the CLLocationManagerDelegate protocol import UIKit UIKit h import CoreLocation CoreLocation h interface LocationViewController UIViewController CLLocationManagerDelegate property strong nonatomic IBOutlet UILabel latitude property strong nonatomic IBOutlet UILabel longitude property strong nonatomic IBOutlet UILabel horizontalAccuracy property strong nonatomic IBOutlet UILabel altitude property strong nonatomic IBOutlet UILabel verticalAccuracy property strong nonatomic IBOutlet UILabel distance property strong nonatomic CLLocationManager locationManager property strong nonatomic CLLocation startLocation IBAction resetDistance id sender end 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 view loads an ideal location is in the view controller s viewDidLoad method in the LocationViewController m file void viewDidLoad super viewDidLoad 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 id sender 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 LocationViewController m file pragma mark pragma mark CLLocationManagerDelegate void locationManager CLLocationManager manager didUpdateToLocation CLLocation newLocation fromLocation CLLocation oldLocation NSString currentLatitude NSString alloc initWithFormat 6f newLocation coordinate latitude latitude text currentLatitude NSString currentLongitude NSString alloc initWithFormat 6f newLocation coordinate longitude longitude text currentLongitude NSString currentHorizontalAccuracy NSString alloc initWithFormat 6f newLocation horizontalAccuracy horizontalAccuracy text currentHorizontalAccuracy NSString currentAltitude NSString alloc initWithFormat 6f newLocation altitude altitude text currentAltitude NSString currentVerticalAccuracy NSString alloc initWithFormat 6f newLocation verticalAccuracy verticalAccuracy text currentVerticalAccuracy if startLocation nil startLocation newLocation CLLocationDistance distanceBetween newLocation

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

  • Working with iOS 6 Maps on the iPad with MapKit and the MKMapView Class - Techotopia
    file Ctrl click on the MKMapView object and drag to a position just below the interface 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 newly created outlet 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 MapSampleViewController h file from the project navigator panel and verify that the outlets and actions have been set up correctly Also take this opportunity to import MapKit MapKit h file and to declare the class as implementing the MKMapViewDelegate protocol import UIKit UIKit h import MapKit MapKit h interface MapSampleViewController UIViewController MKMapViewDelegate property strong nonatomic IBOutlet MKMapView mapView IBAction zoomIn id sender IBAction changeMapType id sender end 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 66 2 google ADSDAQBOX FLOW google Figure 66 2 Configuring the Map View By default the Map View does not indicate the user s current location By setting the showsUserLocation property of the MKMapView class the map is instructed to display a representation of the current location on the map in the form of a blue translucent ball In order to set this property select the MapSampleViewController m file and locate and modify viewDidLoad method as follows void viewDidLoad super viewDidLoad mapView showsUserLocation YES 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 which now needs to be implemented in the mapSampleViewController m file IBAction 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 contains the coordinates of the user Next the MKCoordinateRegionMakeWithDistance function is called in order to generate an MKCoordinateRegion object consisting of the user s location coordinates and a span that stretches

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

  • Using iOS 6 Event Kit to Create iPad Date and Location Based Reminders - Techotopia
    the user s default reminder calendar before being saved to the event store Reminders can be general as in the above example or as will be demonstrated in the following tutorial configured to be triggered at a specific date and time or when the user arrives at or departs from a physical geographical location a concept known as geofencing Creating Alarms The EKAlarm class can be used to add an alarm to the reminder Alarms can be specified either using a specific date and time via a call to alarmWithAbsoluteDate and passing through an NSDate object or using a relative time interval via a call to alarmWithRelativeOffset passing through an NSTimeInterval value Once an EKAlarm object has been created and configured it must be added to the EKReminder object with which the alarm is to be associated When the specified time arrives the user will be notified of the reminder with sound vibration and a notification panel Creating the Example Project Begin by launching Xcode and selecting the options to create a new iPad iOS application based on the Tabbed Application template Enter ReminderApp as the product name and class prefix set the device to iPad and select the Use Storyboards and Use Automatic Reference Counting options if they are not already selected In the remainder of this chapter an application will be constructed designed to allow the user to add reminders based on either date time or location factors Before proceeding display the Settings application on your iPad device select the Reminders app in the list and select a calendar to act as the default for new reminders Designing the User Interface for the Date Time Based Reminder Screen Upon reviewing the MainStoryboard storyboard file it is clear that Xcode has created a template based tabbed application consisting of 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 Reminder App 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 67 4 Figure 67 4 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 ReminderAppFirstViewController h 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 Figure 67 5 Figure 67 5 Ctrl click on the Text Field object in the view and drag the resulting line to the area immediately beneath the interface directive 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 last outlet connection added 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 ReminderAppFirstViewController m file and add an additional property This is also an opportune time to import the EventKit framework headers import UIKit UIKit h import EventKit EventKit h interface ReminderAppFirstViewController UIViewController property strong nonatomic EKEventStore eventStore property strong nonatomic IBOutlet UIDatePicker myDatePicker property strong nonatomic IBOutlet UITextField reminderText IBAction setReminder id sender end Within the project navigator select the ReminderAppFirstViewController m file locate the setReminder template stub and add the following code IBAction setReminder id sender if eventStore nil eventStore EKEventStore alloc init eventStore requestAccessToEntityType EKEntityTypeReminder completion BOOL granted NSError error if granted NSLog Access to store not granted if eventStore nil self createReminder 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 ReminderAppFirstViewController m still in the editing panel implement this method void createReminder EKReminder reminder EKReminder reminderWithEventStore self eventStore reminder title reminderText text reminder calendar eventStore defaultCalendarForNewReminders NSDate date myDatePicker date EKAlarm alarm EKAlarm alarmWithAbsoluteDate date reminder addAlarm alarm NSError error nil eventStore saveReminder reminder commit YES error error if error NSLog error error 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

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

  • Integrating Twitter and Facebook into iPad iOS 6 Applications - Techotopia
    with a button providing the option to add a new Twitter account and switches providing control over which applications may be granted permission to access those Twitter accounts Figure 73 1 The current Facebook account settings on the device may similarly be viewed and modified by selecting the Facebook option of the main screen of the Settings 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 An iOS 6 iPad Twitter Integration Tutorial using SLRequest 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 73 2 will appear listing the options that are available Figure 73 2 Once a destination social network has been selected the preview sheet for the chosen service Figure 73 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 user may then send the message Figure 73 3 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 NSArray 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 NSString postText My first Facebook post from iOS 6 UIImage postImage UIImage imageNamed myImage png NSArray activityItems postText postImage UIActivityViewController activityController UIActivityViewController alloc initWithActivityItems activityItems applicationActivities nil self presentViewController activityController animated YES 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

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

  • An iPad iOS 6 Facebook Integration Tutorial using UIActivityViewController - Techotopia
    Select the Select Image button it may be necessary to click twice since the first click will select the tool bar parent Ctrtl click on the button and drag the resulting line to a position beneath the new outlets previously declared in the Assistant Editor In the resulting configuration panel change the Connection type to Action and name the method selectImage Repeat this step to add an action for the Send Post button this time naming the action sendPost In order to assign an action to the View object it will need to be changed so that it is a subclass of UIControl Click on the background of the view display the Identity Inspector View Utilities Show Identity Inspector and change the object s class from UIView to UIControl Having changed the class Ctrl click on the view background and drag to a position beneath the other actions in the Assistant Editor panel and declare an action connection named hideKeyboard for the Touch Down event Once the connections have been established select the SocialAppViewController h file and further modify it to configure the class to act as an image picker delegate and to add some imports that will be required later in the tutorial import UIKit UIKit h import Social Social h import MobileCoreServices MobileCoreServices h interface SocialAppViewController UIViewController UIImagePickerControllerDelegate UINavigationControllerDelegate UIPopoverControllerDelegate property nonatomic retain UIPopoverController myPopoverController property strong nonatomic IBOutlet UITextView postText property strong nonatomic IBOutlet UIImageView postImage IBAction selectImage id sender IBAction sendPost id sender IBAction hideKeyboard id sender end Implementing the selectImage and Delegate Methods The purpose of the selectImage action method is to provide the user with access to photos on the device and allow one to be selected for inclusion in the Facebook post With these requirements in mind select the SocialAppViewController m file locate the selectImage stub added by the Assistant editor and modify it as follows IBAction selectImage id sender if myPopoverController isPopoverVisible myPopoverController dismissPopoverAnimated YES else 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 myPopoverController UIPopoverController alloc initWithContentViewController imagePicker myPopoverController delegate self myPopoverController presentPopoverFromBarButtonItem sender permittedArrowDirections UIPopoverArrowDirectionUp animated YES void imagePickerController UIImagePickerController picker didFinishPickingMediaWithInfo NSDictionary info myPopoverController dismissPopoverAnimated true NSString mediaType info objectForKey UIImagePickerControllerMediaType self dismissViewControllerAnimated YES completion nil if mediaType isEqualToString NSString kUTTypeImage UIImage image info objectForKey UIImagePickerControllerOriginalImage postImage image image else if mediaType isEqualToString NSString kUTTypeMovie Code here to support video if enabled Next add the other image picker delegate methods so that the picker is dismissed when the user has made a selection pragma mark pragma mark UIImagePickerControllerDelegate void imagePickerController UIImagePickerController picker didFinishPickingMediaWithInfo NSDictionary info NSString mediaType info UIImagePickerControllerMediaType self dismissViewControllerAnimated YES completion nil if mediaType isEqualToString NSString kUTTypeImage UIImage image info UIImagePickerControllerOriginalImage postImage image image void imagePickerControllerDidCancel UIImagePickerController picker self dismissViewControllerAnimated YES completion nil Hiding the Keyboard When the user touches the view object in the background of the user interface we need the keyboard to be removed from view This

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

  • IPad iOS 6 Facebook and Twitter Integration using SLRequest - Techotopia
    on the device Since iOS 6 supports different social networks the request must also include the type of social network for which access is being requested This in turn is represented by an appropriately configured ACAccountType object The following code for example seeks access to the Twitter accounts configured on the device ACAccountStore account ACAccountStore alloc init ACAccountType accountType account accountTypeWithAccountTypeIdentifier ACAccountTypeIdentifierTwitter account requestAccessToAccountsWithType accountType options nil completion BOOL granted NSError error if granted YES Get account and communicate with Twitter API In the event that access is granted an array of Twitter accounts on the device can be obtained via a subsequent call to the accountsWithAccountType method of the account object used for the request The required account may then be extracted from the array of accounts for use in constructing an SLRequest object The following code accesses the array of accounts selects the last account entry and assigns it to twitterAccount ACAccountStore account ACAccountStore alloc init ACAccountType accountType account accountTypeWithAccountTypeIdentifier ACAccountTypeIdentifierTwitter account requestAccessToAccountsWithType accountType options nil completion BOOL granted NSError error if granted YES NSArray arrayOfAccounts account accountsWithAccountType accountType if arrayOfAccounts count 0 ACAccount twitterAccount arrayOfAccounts lastObject The next task is to request an SLRequest object for Twitter access This is achieved via a call to the requestForServiceType class method of the SLRequest class passing through the following values The type of social network service for which the SLRequest will be used in this case SLServiceTypeTwitter The HTTP request method type SLRequestMethodPOST SLRequestMethodGET or SLRequestMethodDELETE The URL required by the social network API for interaction An NSDictionary object containing any parameters required by the social network API to complete the transaction The following code changes request an SLRequest instance configured for sending a Twitter update containing the text My first Twitter post from iOS 6 ACAccountStore account ACAccountStore alloc init ACAccountType accountType account accountTypeWithAccountTypeIdentifier ACAccountTypeIdentifierTwitter account requestAccessToAccountsWithType accountType options nil completion BOOL granted NSError error if granted YES NSArray arrayOfAccounts account accountsWithAccountType accountType if arrayOfAccounts count 0 ACAccount twitterAccount arrayOfAccounts lastObject NSDictionary message status My First Twitter post from iOS 6 NSURL requestURL NSURL URLWithString http api twitter com 1 statuses update json SLRequest postRequest SLRequest requestForServiceType SLServiceTypeTwitter requestMethod SLRequestMethodPOST URL requestURL parameters message Finally the account object needs to be assigned to the SLRequest object and the request posted to the Twitter API ACAccountStore account ACAccountStore alloc init ACAccountType accountType account accountTypeWithAccountTypeIdentifier ACAccountTypeIdentifierTwitter account requestAccessToAccountsWithType accountType options nil completion BOOL granted NSError error if granted YES NSArray arrayOfAccounts account accountsWithAccountType accountType if arrayOfAccounts count 0 ACAccount twitterAccount arrayOfAccounts lastObject NSDictionary message status My First Twitter post from iOS6 NSURL requestURL NSURL URLWithString http api twitter com 1 statuses update json SLRequest postRequest SLRequest requestForServiceType SLServiceTypeTwitter requestMethod SLRequestMethodPOST URL requestURL parameters message postRequest account twitterAccount postRequest performRequestWithHandler NSData responseData NSHTTPURLResponse urlResponse NSError error NSLog Twitter HTTP response i urlResponse statusCode For the purposes of this example the handler for the performRequestWithHandler method simply outputs the HTTP response code for the request to the console The above coding example

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

  • An iOS 6 iPad Twitter Integration Tutorial using SLRequest - Techotopia
    access the Twitter account and extract the posts from the account timeline will reside in a method named getTimeLine located in the TwitterAppViewController m file Select this file and modify it to add the code for this new method void getTimeLine ACAccountStore account ACAccountStore alloc init ACAccountType accountType account accountTypeWithAccountTypeIdentifier ACAccountTypeIdentifierTwitter account requestAccessToAccountsWithType accountType options nil completion BOOL granted NSError error if granted YES NSArray arrayOfAccounts account accountsWithAccountType accountType if arrayOfAccounts count 0 ACAccount twitterAccount arrayOfAccounts lastObject NSURL requestURL NSURL URLWithString http api twitter com 1 statuses home timeline json NSMutableDictionary parameters NSMutableDictionary alloc init parameters setObject 20 forKey count parameters setObject 1 forKey include entities SLRequest postRequest SLRequest requestForServiceType SLServiceTypeTwitter requestMethod SLRequestMethodGET URL requestURL parameters parameters postRequest account twitterAccount postRequest performRequestWithHandler NSData responseData NSHTTPURLResponse urlResponse NSError error self dataSource NSJSONSerialization JSONObjectWithData responseData options NSJSONReadingMutableLeaves error error if self dataSource count 0 dispatch async dispatch get main queue self tweetTableView reloadData else Handle failure to get account access Much of the code in this method will be familiar from the previous chapter There are however some notable exceptions Firstly the URL used in the request is intended to return the entries in the time line of the user s Twitter account NSURL requestURL NSURL URLWithString http api twitter com 1 statuses home timeline json The URL specified requires additional parameters specifying how much data is to be returned In this case the request is limited to the 25 most recent posts and configured to include the tweet entities NSMutableDictionary parameters NSMutableDictionary alloc init parameters setObject 25 forKey count parameters setObject 1 forKey include entities The SLRequest object is primed to use the SLRequestMethodGET HTTP method This is appropriate since this time we are getting as opposed to posting data SLRequest postRequest SLRequest requestForServiceType SLServiceTypeTwitter requestMethod SLRequestMethodGET URL requestURL parameters parameters Finally the handler code for the postRequest method call now accesses the returned NSData object The NSJSONSerialization class is then used to parse and serialize the data returned and assign it to the dataSource NSArray object The Table View object is then told to reload the data it is displaying causing it to re read the data in the dataSource array and display it to the user An important point to note here is that iOS performs the Twitter API request in a different thread from the main thread of the application Threads are the cornerstone of any multitasking operating system and can be thought of as mini processes running within a main process the purpose of which is to enable at least the appearance of parallel execution paths within applications Since user interface updates take place in the main thread of the application code has been added to ensure that the Table View reload call is made in the main thread as opposed to the thread used for the post request postRequest performRequestWithHandler NSData responseData NSHTTPURLResponse urlResponse NSError error self dataSource NSJSONSerialization JSONObjectWithData responseData options NSJSONReadingMutableLeaves error error if self dataSource count 0 dispatch async dispatch get main queue

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



  •