SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
iPhone Application Development II
            Janet Huang
             2011/11/30
Today’s topic
• Model View Control
• Protocol, Delegation, Target/Action
• Location in iPhone
 • CoreLocation
 • MapKit
• Location-based iPhone Application
MVC
                          should
                                   did
                       will                 target

                       controller
                                          outlet
                      count
Notification




                                          de
                         data




                                   da
 & KVO




                                             le
                                     ta

                                             ga
                                                        action




                                               te
                                         so
                                           urc
                                           es
              model                                  view
IBOutlet & IBAction
                     target                  action



        controller                                    view
                   outlet




#import <UIKit/UIKit.h>

@interface HelloViewController : UIViewController
{
    IBOutlet UILabel* display;
}

- (IBAction)pressButton:(id)sender;
@end
                                                             Interface Builder
                            ViewController
Delegation pattern


                    delegate        delegate
delegator                        (helper object)
class RealPrinter { // the "delegate"
    void print() {
      System.out.print("something");
    }
}

class Printer { // the "delegator"
    RealPrinter p = new RealPrinter(); // create the delegate
    void print() {
      p.print(); // delegation
    }
}

public class Main {
    // to the outside world it looks like Printer actually prints.
    public static void main(String[] args) {
        Printer printer = new Printer();
        printer.print();
    }
}




                                             java simple example
interface I {
    void f();
    void g();
}

class A implements I {
    public void f() { System.out.println("A: doing f()"); }
    public void g() { System.out.println("A: doing g()"); }
}

class B implements I {
    public void f() { System.out.println("B: doing f()"); }
    public void g() { System.out.println("B: doing g()"); }
}

class C implements I {
    // delegation
    I i = new A();

    public void f() { i.f(); }
    public void g() { i.g(); }

    // normal attributes
    public void toA() { i = new A(); }
    public void toB() { i = new B(); }
}

public class Main {
    public static void main(String[] args) {
        C c = new C();
        c.f();      // output: A: doing f()
        c.g();      // output: A: doing g()
        c.toB();
        c.f();      // output: B: doing f()
        c.g();      // output: B: doing g()
    }
}
                                           java complex example
@protocol I <NSObject>
-(void) f;
-(void) g;
@end

@interface A : NSObject <I> { }             // constructor
@end                                        -(id)init {
@implementation A                               if (self = [super init]) { i = [[A alloc] init]; }
-(void) f { NSLog(@"A: doing f"); }             return self;
-(void) g { NSLog(@"A: doing g"); }         }
@end
                                            // destructor
@interface B : NSObject <I> { }             -(void)dealloc { [i release]; [super dealloc]; }
@end                                        @end
@implementation B
-(void) f { NSLog(@"B: doing f"); }         int main (int argc, const char    * argv[]) {
-(void) g { NSLog(@"B: doing g"); }             NSAutoreleasePool * pool =    [[NSAutoreleasePool alloc]
@end                                        init];
                                                C *c = [[C alloc] init];
@interface C : NSObject <I> {                   [c f];                   //   output: A: doing f
     id<I> i; // delegation                     [c g];                   //   output: A: doing g
}                                               [c toB];
-(void) toA;                                    [c f];                   //   output: B: doing f
-(void) toB;                                    [c g];                   //   output: B: doing g
@end                                            [c release];
                                                [pool drain];
@implementation C                               return 0;
-(void) f { [i f]; }                        }
-(void) g { [i g]; }

-(void) toA { [i release]; i = [[A alloc]
init]; }
-(void) toB { [i release]; i = [[B alloc]
init]; }
Delegation
     •    Delegate: a helper object can execute a task for the delegator

     •    Delegator: delegate a task to the delegate



                                    delegate
   CLLocationManagerDelegate                       MyCoreLocationController


           the delegator                                   the delegate
         (declare methods)                             (implement methods)



@interface MyCoreLocationController : NSObject <CLLocationManagerDelegate>

                                                                    protocol
Location in iPhone
• Core Location
 • framework for specifying location on the
    planet
• MapKit
 • graphical toolkit for displaying locations
    on the planet
CoreLocation
• A frameworks to manage location and
  heading
 •   CLLocation (basic object)

 •   CLLocationManager

 •   CLHeading

• No UI
• How to get CLLocation?
 •   use CLLocationManager
CoreLocation
•   Where is the location? (approximately)

    @property (readonly) CLLocationCoordinate2D coordinate;
    typedef {
       CLLocationDegrees latitude;
       CLLocationDegrees longitude;
    } CLLocationCoordinate2D;

    //meters A negative value means “below sea level.”
    @property(readonly)CLLocationDistancealtitude;
CoreLocation
• How does it know the location?
 • GPS
 • Wifi
 • Cell network
• The more accurate the technology, the
  more power it costs
CLLocationManager
• General approach
 •   Check to see if the hardware you are on/user
     supports the kind of location updating you want.

 •    Create a CLLocationManager instance and set a
     delegate to receive updates.

 •   Configure the manager according to what kind
     of location updating you want.

 •   Start the manager monitoring for location
     changes.
CoreLocation
•   Accuracy-based continuous location monitoring
        @propertyCLLocationAccuracydesiredAccuracy;
        @property CLLocationDistance distanceFilter;
•   Start the monitoring
        - (void)startUpdatingLocation;
        - (void)stopUpdatingLocation;

•   Get notified via the CLLocationManager’s
    delegate
      - (void)locationManager:(CLLocationManager *)manager
         didUpdateToLocation:(CLLocation *)newLocation
               fromLocation:(CLLocation *)oldLocation;
MapKit

•   Display a map

•   Show user location

•   Add annotations on a map
MKMapView

• 2 ways to create a map
 • create with alloc/init
 • drag from Library in Interface builder
• MKAnnotation
MKMapView
 •    Controlling the region the map is displaying
       @property MKCoordinateRegion region;
       typedef struct {
           CLLocationCoordinate2D center;
           MKCoordinateSpan span;
       } MKCoordinateRegion;
       typedef struct {
           CLLocationDegrees latitudeDelta;
           CLLocationDegrees longitudeDelta;
       }
       // animated version
       - (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated;

 •    Can also set the center point only
@property CLLocationCoordinate2D centerCoordinate;
- (void)setCenterCoordinate:(CLLocationCoordinate2D)center animated:(BOOL)animated;
MKAnnotation
How to add an annotation on a map?
  - implement a customized annotation using MKAnnotation protocol
        @protocol MKAnnotation <NSObject>
        @property (readonly) CLLocationCoordinate2D coordinate;
        @optional
        @property (readonly) NSString *title;
        @property (readonly) NSString *subtitle;
        @end
        typedef {
           CLLocationDegrees latitude;
           CLLocationDegrees longitude;
        } CLLocationCoordinate2D;

 - add annotation to MKMapView
        [mapView addAnnotation:myannotation];
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MyAnnotation : NSObject <MKAnnotation>
{
    CLLocationCoordinate2D coordinate;
    NSString * title;
    NSString * subtitle;
}
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString * title;
@property (nonatomic, copy) NSString * subtitle;

- (id)initWithCoordinate:(CLLocationCoordinate2D)coord;

@end                                                       MyAnnotation.h


#import "MyAnnotation.h"

@implementation MyAnnotation

@synthesize coordinate;
@synthesize title;
@synthesize subtitle;

- (id)initWithCoordinate:(CLLocationCoordinate2D)coord {
    self = [super init];
    if (self) {
        coordinate = coord;
    }
    return self;
}

- (void) dealloc
{
     [title release];
! [subtitle release];
     [super dealloc];
}
@end                                                       MyAnnotation.m
Google Map API
A geolocation api request:
  http://maps.googleapis.com/maps/api/geocode/output?parameters

  https://maps.googleapis.com/maps/api/geocode/output?parameters



URL parameters:
    - address (required)
    - latlng (required)
    - sensor (required)
    - bounds
    - region
    - language
                             http://code.google.com/apis/maps/documentation/geocoding/
http://maps.googleapis.com/maps/api/geocode/json?address=台北
101&sensor=true
      {
          "results" : [
             {
                "address_components" : [
                   {
                      "long_name" : "101縣道",
                      "short_name" : "101縣道",
                      "types" : [ "route" ]
                   },
                   {
                      "long_name" : "New Taipei City",
                      "short_name" : "New Taipei City",
                      "types" : [ "administrative_area_level_2", "political" ]
                   },
                   {
                      "long_name" : "Taiwan",
                      "short_name" : "TW",
                      "types" : [ "country", "political" ]
                   }
                ],
                "formatted_address" : "Taiwan, New Taipei City, 101縣道",
                "geometry" : {
                   "bounds" : {
                      "northeast" : {
                         "lat" : 25.26163510,
                         "lng" : 121.51636480
                      },
                      "southwest" : {
                         "lat" : 25.17235040,
                         "lng" : 121.44038660
http://maps.googleapis.com/maps/api/geocode/xml?address=
台北101&sensor=true

     <?xml version="1.0" encoding="UTF-8"?>
     <GeocodeResponse>
      <status>OK</status>
      <result>
       <type>route</type>
       <formatted_address>Taiwan, New Taipei City, 101縣道</formatted_address>
       <address_component>
        <long_name>101縣道</long_name>
        <short_name>101縣道</short_name>
        <type>route</type>
       </address_component>
       <address_component>
        <long_name>New Taipei City</long_name>
        <short_name>New Taipei City</short_name>
        <type>administrative_area_level_2</type>
        <type>political</type>
       </address_component>
       <address_component>
        <long_name>Taiwan</long_name>
        <short_name>TW</short_name>
        <type>country</type>
        <type>political</type>
       </address_component>
       <geometry>
        <location>
         <lat>25.2012026</lat>
http://maps.google.com/maps/geo?q=台北101

   {
       "name": "台北101",
       "Status": {
          "code": 200,
          "request": "geocode"
       },
       "Placemark": [ {
          "id": "p1",
          "address": "Taiwan, New Taipei City, 101縣道",
          "AddressDetails": {
        "Accuracy" : 6,
        "Country" : {
            "AdministrativeArea" : {
               "AdministrativeAreaName" : "新北市",
               "Thoroughfare" : {
                  "ThoroughfareName" : "101縣道"
               }




http://maps.google.com/maps/geo?q=台北101&output=csv

   200,6,25.2012026,121.4937590
Location-based iPhone Implementation
Hello Location




                 - get user current location
                 - show a map
                 - show current location
                 - show location information
Hello Map




            - add an annotation on a map
            - add title and subtitle on this
            annotation
Hello Address




                - query an address using google
                geolocation api
                - show the result on the map

Contenu connexe

Similaire à Iphone course 2

Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Sarp Erdag
 
Building a p2 update site using Buckminster
Building a p2 update site using BuckminsterBuilding a p2 update site using Buckminster
Building a p2 update site using Buckminster
guest5e2b6b
 
Maximilian Michels – Google Cloud Dataflow on Top of Apache Flink
Maximilian Michels – Google Cloud Dataflow on Top of Apache FlinkMaximilian Michels – Google Cloud Dataflow on Top of Apache Flink
Maximilian Michels – Google Cloud Dataflow on Top of Apache Flink
Flink Forward
 

Similaire à Iphone course 2 (20)

iOS
iOSiOS
iOS
 
Pioc
PiocPioc
Pioc
 
Objective-Cひとめぐり
Objective-CひとめぐりObjective-Cひとめぐり
Objective-Cひとめぐり
 
Day 1
Day 1Day 1
Day 1
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
 
Core Location and Map Kit: Bringing Your Own Maps [Voices That Matter: iPhone...
Core Location and Map Kit: Bringing Your Own Maps [Voices That Matter: iPhone...Core Location and Map Kit: Bringing Your Own Maps [Voices That Matter: iPhone...
Core Location and Map Kit: Bringing Your Own Maps [Voices That Matter: iPhone...
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
angular fundamentals.pdf
angular fundamentals.pdfangular fundamentals.pdf
angular fundamentals.pdf
 
303 TANSTAAFL: Using Open Source iPhone UI Code
303 TANSTAAFL: Using Open Source iPhone UI Code303 TANSTAAFL: Using Open Source iPhone UI Code
303 TANSTAAFL: Using Open Source iPhone UI Code
 
Building a p2 update site using Buckminster
Building a p2 update site using BuckminsterBuilding a p2 update site using Buckminster
Building a p2 update site using Buckminster
 
Maximilian Michels – Google Cloud Dataflow on Top of Apache Flink
Maximilian Michels – Google Cloud Dataflow on Top of Apache FlinkMaximilian Michels – Google Cloud Dataflow on Top of Apache Flink
Maximilian Michels – Google Cloud Dataflow on Top of Apache Flink
 
The 2016 Android Developer Toolbox [NANTES]
The 2016 Android Developer Toolbox [NANTES]The 2016 Android Developer Toolbox [NANTES]
The 2016 Android Developer Toolbox [NANTES]
 
Map kit light
Map kit lightMap kit light
Map kit light
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
Spring boot
Spring boot Spring boot
Spring boot
 
The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]
 

Plus de Janet Huang (13)

Transferring Sensing to a Mixed Virtual and Physical Experience
Transferring Sensing to a Mixed Virtual and Physical ExperienceTransferring Sensing to a Mixed Virtual and Physical Experience
Transferring Sensing to a Mixed Virtual and Physical Experience
 
Collecting a Image Label from Crowds Using Amazon Mechanical Turk
Collecting a Image Label from Crowds Using Amazon Mechanical TurkCollecting a Image Label from Crowds Using Amazon Mechanical Turk
Collecting a Image Label from Crowds Using Amazon Mechanical Turk
 
Art in the Crowd
Art in the CrowdArt in the Crowd
Art in the Crowd
 
How to Program SmartThings
How to Program SmartThingsHow to Program SmartThings
How to Program SmartThings
 
Designing physical and digital experience in social web
Designing physical and digital experience in social webDesigning physical and digital experience in social web
Designing physical and digital experience in social web
 
Of class3
Of class3Of class3
Of class3
 
Of class2
Of class2Of class2
Of class2
 
Of class1
Of class1Of class1
Of class1
 
Iphone course 3
Iphone course 3Iphone course 3
Iphone course 3
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
 
The power of example
The power of exampleThe power of example
The power of example
 
Responsive web design
Responsive web designResponsive web design
Responsive web design
 
Openframworks x Mobile
Openframworks x MobileOpenframworks x Mobile
Openframworks x Mobile
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Iphone course 2

  • 1. iPhone Application Development II Janet Huang 2011/11/30
  • 2. Today’s topic • Model View Control • Protocol, Delegation, Target/Action • Location in iPhone • CoreLocation • MapKit • Location-based iPhone Application
  • 3. MVC should did will target controller outlet count Notification de data da & KVO le ta ga action te so urc es model view
  • 4. IBOutlet & IBAction target action controller view outlet #import <UIKit/UIKit.h> @interface HelloViewController : UIViewController { IBOutlet UILabel* display; } - (IBAction)pressButton:(id)sender; @end Interface Builder ViewController
  • 5. Delegation pattern delegate delegate delegator (helper object)
  • 6. class RealPrinter { // the "delegate" void print() { System.out.print("something"); } } class Printer { // the "delegator" RealPrinter p = new RealPrinter(); // create the delegate void print() { p.print(); // delegation } } public class Main { // to the outside world it looks like Printer actually prints. public static void main(String[] args) { Printer printer = new Printer(); printer.print(); } } java simple example
  • 7. interface I { void f(); void g(); } class A implements I { public void f() { System.out.println("A: doing f()"); } public void g() { System.out.println("A: doing g()"); } } class B implements I { public void f() { System.out.println("B: doing f()"); } public void g() { System.out.println("B: doing g()"); } } class C implements I { // delegation I i = new A(); public void f() { i.f(); } public void g() { i.g(); } // normal attributes public void toA() { i = new A(); } public void toB() { i = new B(); } } public class Main { public static void main(String[] args) { C c = new C(); c.f(); // output: A: doing f() c.g(); // output: A: doing g() c.toB(); c.f(); // output: B: doing f() c.g(); // output: B: doing g() } } java complex example
  • 8. @protocol I <NSObject> -(void) f; -(void) g; @end @interface A : NSObject <I> { } // constructor @end -(id)init { @implementation A if (self = [super init]) { i = [[A alloc] init]; } -(void) f { NSLog(@"A: doing f"); } return self; -(void) g { NSLog(@"A: doing g"); } } @end // destructor @interface B : NSObject <I> { } -(void)dealloc { [i release]; [super dealloc]; } @end @end @implementation B -(void) f { NSLog(@"B: doing f"); } int main (int argc, const char * argv[]) { -(void) g { NSLog(@"B: doing g"); } NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] @end init]; C *c = [[C alloc] init]; @interface C : NSObject <I> { [c f]; // output: A: doing f id<I> i; // delegation [c g]; // output: A: doing g } [c toB]; -(void) toA; [c f]; // output: B: doing f -(void) toB; [c g]; // output: B: doing g @end [c release]; [pool drain]; @implementation C return 0; -(void) f { [i f]; } } -(void) g { [i g]; } -(void) toA { [i release]; i = [[A alloc] init]; } -(void) toB { [i release]; i = [[B alloc] init]; }
  • 9. Delegation • Delegate: a helper object can execute a task for the delegator • Delegator: delegate a task to the delegate delegate CLLocationManagerDelegate MyCoreLocationController the delegator the delegate (declare methods) (implement methods) @interface MyCoreLocationController : NSObject <CLLocationManagerDelegate> protocol
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15. Location in iPhone • Core Location • framework for specifying location on the planet • MapKit • graphical toolkit for displaying locations on the planet
  • 16. CoreLocation • A frameworks to manage location and heading • CLLocation (basic object) • CLLocationManager • CLHeading • No UI • How to get CLLocation? • use CLLocationManager
  • 17. CoreLocation • Where is the location? (approximately) @property (readonly) CLLocationCoordinate2D coordinate; typedef { CLLocationDegrees latitude; CLLocationDegrees longitude; } CLLocationCoordinate2D; //meters A negative value means “below sea level.” @property(readonly)CLLocationDistancealtitude;
  • 18. CoreLocation • How does it know the location? • GPS • Wifi • Cell network • The more accurate the technology, the more power it costs
  • 19. CLLocationManager • General approach • Check to see if the hardware you are on/user supports the kind of location updating you want. • Create a CLLocationManager instance and set a delegate to receive updates. • Configure the manager according to what kind of location updating you want. • Start the manager monitoring for location changes.
  • 20. CoreLocation • Accuracy-based continuous location monitoring @propertyCLLocationAccuracydesiredAccuracy; @property CLLocationDistance distanceFilter; • Start the monitoring - (void)startUpdatingLocation; - (void)stopUpdatingLocation; • Get notified via the CLLocationManager’s delegate - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
  • 21. MapKit • Display a map • Show user location • Add annotations on a map
  • 22. MKMapView • 2 ways to create a map • create with alloc/init • drag from Library in Interface builder • MKAnnotation
  • 23. MKMapView • Controlling the region the map is displaying @property MKCoordinateRegion region; typedef struct { CLLocationCoordinate2D center; MKCoordinateSpan span; } MKCoordinateRegion; typedef struct { CLLocationDegrees latitudeDelta; CLLocationDegrees longitudeDelta; } // animated version - (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated; • Can also set the center point only @property CLLocationCoordinate2D centerCoordinate; - (void)setCenterCoordinate:(CLLocationCoordinate2D)center animated:(BOOL)animated;
  • 24. MKAnnotation How to add an annotation on a map? - implement a customized annotation using MKAnnotation protocol @protocol MKAnnotation <NSObject> @property (readonly) CLLocationCoordinate2D coordinate; @optional @property (readonly) NSString *title; @property (readonly) NSString *subtitle; @end typedef { CLLocationDegrees latitude; CLLocationDegrees longitude; } CLLocationCoordinate2D; - add annotation to MKMapView [mapView addAnnotation:myannotation];
  • 25. #import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface MyAnnotation : NSObject <MKAnnotation> { CLLocationCoordinate2D coordinate; NSString * title; NSString * subtitle; } @property (nonatomic, assign) CLLocationCoordinate2D coordinate; @property (nonatomic, copy) NSString * title; @property (nonatomic, copy) NSString * subtitle; - (id)initWithCoordinate:(CLLocationCoordinate2D)coord; @end MyAnnotation.h #import "MyAnnotation.h" @implementation MyAnnotation @synthesize coordinate; @synthesize title; @synthesize subtitle; - (id)initWithCoordinate:(CLLocationCoordinate2D)coord { self = [super init]; if (self) { coordinate = coord; } return self; } - (void) dealloc { [title release]; ! [subtitle release]; [super dealloc]; } @end MyAnnotation.m
  • 26. Google Map API A geolocation api request: http://maps.googleapis.com/maps/api/geocode/output?parameters https://maps.googleapis.com/maps/api/geocode/output?parameters URL parameters: - address (required) - latlng (required) - sensor (required) - bounds - region - language http://code.google.com/apis/maps/documentation/geocoding/
  • 27. http://maps.googleapis.com/maps/api/geocode/json?address=台北 101&sensor=true { "results" : [ { "address_components" : [ { "long_name" : "101縣道", "short_name" : "101縣道", "types" : [ "route" ] }, { "long_name" : "New Taipei City", "short_name" : "New Taipei City", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Taiwan", "short_name" : "TW", "types" : [ "country", "political" ] } ], "formatted_address" : "Taiwan, New Taipei City, 101縣道", "geometry" : { "bounds" : { "northeast" : { "lat" : 25.26163510, "lng" : 121.51636480 }, "southwest" : { "lat" : 25.17235040, "lng" : 121.44038660
  • 28. http://maps.googleapis.com/maps/api/geocode/xml?address= 台北101&sensor=true <?xml version="1.0" encoding="UTF-8"?> <GeocodeResponse> <status>OK</status> <result> <type>route</type> <formatted_address>Taiwan, New Taipei City, 101縣道</formatted_address> <address_component> <long_name>101縣道</long_name> <short_name>101縣道</short_name> <type>route</type> </address_component> <address_component> <long_name>New Taipei City</long_name> <short_name>New Taipei City</short_name> <type>administrative_area_level_2</type> <type>political</type> </address_component> <address_component> <long_name>Taiwan</long_name> <short_name>TW</short_name> <type>country</type> <type>political</type> </address_component> <geometry> <location> <lat>25.2012026</lat>
  • 29. http://maps.google.com/maps/geo?q=台北101 { "name": "台北101", "Status": { "code": 200, "request": "geocode" }, "Placemark": [ { "id": "p1", "address": "Taiwan, New Taipei City, 101縣道", "AddressDetails": { "Accuracy" : 6, "Country" : { "AdministrativeArea" : { "AdministrativeAreaName" : "新北市", "Thoroughfare" : { "ThoroughfareName" : "101縣道" } http://maps.google.com/maps/geo?q=台北101&output=csv 200,6,25.2012026,121.4937590
  • 31. Hello Location - get user current location - show a map - show current location - show location information
  • 32. Hello Map - add an annotation on a map - add title and subtitle on this annotation
  • 33. Hello Address - query an address using google geolocation api - show the result on the map