SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
iPhone	
  Development:	
  
       H"p	
  Connec*on	
  

             Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
H>p	
  Connec@on	
  
•  NSUrlConnection
   –  Easiest	
  way	
  to	
  download	
  the	
  contents	
  of	
  an	
  URL	
  
•  Crea@ng	
  connec@on	
  
•  Canceling	
  connec@on	
  
•  Collec@on	
  of	
  delegate	
  methods	
  for	
  controlling	
  
   the	
  connec@on	
  
Crea@ng	
  a	
  Connec@on	
  
// Create the request
NSURLRequest *theRequest=
     [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.tamk.fi"]
                      cachePolicy: NSURLRequestUseProtocolCachePolicy
                  timeoutInterval: 60.0];

// Create the connection with the request
// and start loading the data
NSURLConnection *theConnection=
     [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if ( theConnection )
{
    // Create the NSMutableData that will hold
    // the received data (A wrapper for byte buffer)
    // receivedData is declared as a method instance elsewhere .
    // Creates empty data wrapper.
    receivedData = [ [NSMutableData data] retain ];
} else
{
    // inform the user that the download could not be made
}
Delegate?	
  
// Create the connection with the request
// and start loading the data
NSURLConnection *theConnection=
     [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

//     Now "self" must conform to the delegate methods that are:
//     - (void) connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response
//     - (void) connection:(NSURLConnection*) connection didFailWithError:(NSError *) error
//     - (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data
//     - (void) connectionDidFinishLoading:(NSURLConnection *) connection
	
  
// These methods are are now called automatically!
URLConnec@on	
  class	
  
@interface URLConnection : NSObject
{
    // Contents of the URL
    NSMutableData* receivedData;
    NSURLConnection* theConnection;
}
// Make the connection
- (void) connect: (NSString* url);

// Cancel the connection
- (void) cancel;

// Delegate methods
- (void) connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse*)
    response
- (void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error
- (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data
- (void) connectionDidFinishLoading:(NSURLConnection*) connection
Connec@ng	
  
- (void) connect:(NSString*) url
{
    // create the request
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];

    // create the connection with the request
    // and start loading the data
    self.theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if( theConnection )
    {
         receivedData=[[NSMutableData data] retain];
    }
    else
    {
         // Connection failed
         // Give error message
    }
}
Receiving	
  data	
  
- (void) connection:(NSURLConnection*) connection
   didReceiveData:(NSData*) data
{
    [receivedData appendData:data];
}
When	
  connec@on	
  is	
  finished	
  
- (void) connectionDidFinishLoading:(NSURLConnection *) connection
{
    // Create byte array from the received data
    unsigned char byteBuffer[[receivedData length]];
    [receivedData getBytes:byteBuffer];

    NSString *temp = [[NSString alloc]
                      initWithBytes:byteBuffer
                             length:[receivedData length]
                           encoding:4];

    // Do something with the data.. For example
    // make a call back method for the viewController

    [temp release];
    [connection release];
    [receivedData release];
    self.theConnection = nil;
}
When	
  failes..	
  
- (void) connection:(NSURLConnection *) connection
   didFailWithError:(NSError *) error
{
   // Error handling
}
Canceling	
  
- (void) cancel
{
    if ( self.theConnection )
    {
        [self.theConnection cancel];
        [self.theConnection release];
    }
}
Usage	
  
[URLConnection *myConn = [[URLConnection alloc] init];
[myConn connect:@"http://www.tamk.fi"];
CallBack	
  Methods?	
  
@interface URLConnection : NSObject
{
    // Contents of the URL
    NSMutableData* receivedData;
    NSURLConnection* theConnection;
    MyViewController* myViewController;
}

- (id) initWithHost:(MyViewController*) host
{
    self = [super init];
    self.myViewController = host;
    self.theConnection    = nil;
    return self;
}

// Make the connection
- (void) connect: (NSString* url);

// Cancel the connection
- (void) cancel;

// Delegate methods
- (void) connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse*)response
- (void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error
- (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data
- (void) connectionDidFinishLoading:(NSURLConnection*) connection
Usage	
  
// We are now in some ViewController class
[URLConnection *myConn = [[URLConnection alloc] initWithHost: self];
[myConn connect:@"http://www.tamk.fi"];
When	
  connec@on	
  is	
  finished	
  
- (void) connectionDidFinishLoading:(NSURLConnection *) connection
{
    unsigned char byteBuffer[[receivedData length]];

    [receivedData getBytes:byteBuffer];

    NSString *temp = [[NSString alloc]
                      initWithBytes:byteBuffer
                             length:[receivedData length]
                           encoding:4];

    // Do something with the data.. For example
    // make a call back method for the viewController
    [myViewController setThisTextToTextView: temp];

    [temp release];
    [connection release];
    [receivedData release];
    self.theConnection = nil;
}

Mais conteúdo relacionado

Mais procurados

C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT III
Minu Rajasekaran
 
Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010
Ismael Celis
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
Technopark
 

Mais procurados (19)

C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT III
 
Mobile Programming - Network Universitas Budi Luhur
Mobile Programming - Network Universitas Budi LuhurMobile Programming - Network Universitas Budi Luhur
Mobile Programming - Network Universitas Budi Luhur
 
The love child of Android and .NET: App development with Xamarin
The love child of Android and .NET: App development with XamarinThe love child of Android and .NET: App development with Xamarin
The love child of Android and .NET: App development with Xamarin
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Introducing Docker to Mac Management – Nick McSpadden
Introducing Docker to Mac Management – Nick McSpaddenIntroducing Docker to Mac Management – Nick McSpadden
Introducing Docker to Mac Management – Nick McSpadden
 
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
 
Phd3
Phd3Phd3
Phd3
 
RegistryModClass
RegistryModClassRegistryModClass
RegistryModClass
 
Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010
 
Node.js and websockets intro
Node.js and websockets introNode.js and websockets intro
Node.js and websockets intro
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Async task
Async taskAsync task
Async task
 
Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.js
 
Tornado web
Tornado webTornado web
Tornado web
 
Couch to OpenStack: Neutron (Quantum) - August 13, 2013 Featuring Sean Winn
Couch to OpenStack: Neutron (Quantum) - August 13, 2013 Featuring Sean WinnCouch to OpenStack: Neutron (Quantum) - August 13, 2013 Featuring Sean Winn
Couch to OpenStack: Neutron (Quantum) - August 13, 2013 Featuring Sean Winn
 
[213] ethereum
[213] ethereum[213] ethereum
[213] ethereum
 
Performance from the user's perspective
Performance from the user's perspectivePerformance from the user's perspective
Performance from the user's perspective
 
Couch to open_stack_keystone
Couch to open_stack_keystoneCouch to open_stack_keystone
Couch to open_stack_keystone
 

Semelhante a iPhone: Http Connection

Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
Whymca
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
celenarouzie
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
Taras Kalapun
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
Robert Nyman
 
Sitecore 7: A developers quest to mastering unit testing
Sitecore 7: A developers quest to mastering unit testingSitecore 7: A developers quest to mastering unit testing
Sitecore 7: A developers quest to mastering unit testing
nonlinear creations
 

Semelhante a iPhone: Http Connection (20)

I os 13
I os 13I os 13
I os 13
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile Devices
 
iPhone and Rails integration
iPhone and Rails integrationiPhone and Rails integration
iPhone and Rails integration
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & Deitel
 
Statying Alive - Online and OFfline
Statying Alive - Online and OFflineStatying Alive - Online and OFfline
Statying Alive - Online and OFfline
 
Working with AFNetworking
Working with AFNetworkingWorking with AFNetworking
Working with AFNetworking
 
Moar tools for asynchrony!
Moar tools for asynchrony!Moar tools for asynchrony!
Moar tools for asynchrony!
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
iOS5 NewStuff
iOS5 NewStuffiOS5 NewStuff
iOS5 NewStuff
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
Effective iOS Network Programming Techniques
Effective iOS Network Programming TechniquesEffective iOS Network Programming Techniques
Effective iOS Network Programming Techniques
 
Advanced data access with Dapper
Advanced data access with DapperAdvanced data access with Dapper
Advanced data access with Dapper
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
Web sockets Introduction
Web sockets IntroductionWeb sockets Introduction
Web sockets Introduction
 
Concurrent networking - made easy
Concurrent networking - made easyConcurrent networking - made easy
Concurrent networking - made easy
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
 
Sitecore 7: A developers quest to mastering unit testing
Sitecore 7: A developers quest to mastering unit testingSitecore 7: A developers quest to mastering unit testing
Sitecore 7: A developers quest to mastering unit testing
 

Mais de Jussi Pohjolainen

Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 

Mais de Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Último

ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
ashishpaul799
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff
17thcssbs2
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
SaadHumayun7
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 

Último (20)

TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
Keeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security ServicesKeeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security Services
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTelling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
 
How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
Mbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxMbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptx
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdfPost Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 

iPhone: Http Connection

  • 1. iPhone  Development:   H"p  Connec*on   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2. H>p  Connec@on   •  NSUrlConnection –  Easiest  way  to  download  the  contents  of  an  URL   •  Crea@ng  connec@on   •  Canceling  connec@on   •  Collec@on  of  delegate  methods  for  controlling   the  connec@on  
  • 3. Crea@ng  a  Connec@on   // Create the request NSURLRequest *theRequest= [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.tamk.fi"] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 60.0]; // Create the connection with the request // and start loading the data NSURLConnection *theConnection= [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if ( theConnection ) { // Create the NSMutableData that will hold // the received data (A wrapper for byte buffer) // receivedData is declared as a method instance elsewhere . // Creates empty data wrapper. receivedData = [ [NSMutableData data] retain ]; } else { // inform the user that the download could not be made }
  • 4. Delegate?   // Create the connection with the request // and start loading the data NSURLConnection *theConnection= [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; // Now "self" must conform to the delegate methods that are: // - (void) connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response // - (void) connection:(NSURLConnection*) connection didFailWithError:(NSError *) error // - (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data // - (void) connectionDidFinishLoading:(NSURLConnection *) connection   // These methods are are now called automatically!
  • 5. URLConnec@on  class   @interface URLConnection : NSObject { // Contents of the URL NSMutableData* receivedData; NSURLConnection* theConnection; } // Make the connection - (void) connect: (NSString* url); // Cancel the connection - (void) cancel; // Delegate methods - (void) connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse*) response - (void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error - (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data - (void) connectionDidFinishLoading:(NSURLConnection*) connection
  • 6. Connec@ng   - (void) connect:(NSString*) url { // create the request NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // create the connection with the request // and start loading the data self.theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if( theConnection ) { receivedData=[[NSMutableData data] retain]; } else { // Connection failed // Give error message } }
  • 7. Receiving  data   - (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data { [receivedData appendData:data]; }
  • 8. When  connec@on  is  finished   - (void) connectionDidFinishLoading:(NSURLConnection *) connection { // Create byte array from the received data unsigned char byteBuffer[[receivedData length]]; [receivedData getBytes:byteBuffer]; NSString *temp = [[NSString alloc] initWithBytes:byteBuffer length:[receivedData length] encoding:4]; // Do something with the data.. For example // make a call back method for the viewController [temp release]; [connection release]; [receivedData release]; self.theConnection = nil; }
  • 9. When  failes..   - (void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error { // Error handling }
  • 10. Canceling   - (void) cancel { if ( self.theConnection ) { [self.theConnection cancel]; [self.theConnection release]; } }
  • 11. Usage   [URLConnection *myConn = [[URLConnection alloc] init]; [myConn connect:@"http://www.tamk.fi"];
  • 12. CallBack  Methods?   @interface URLConnection : NSObject { // Contents of the URL NSMutableData* receivedData; NSURLConnection* theConnection; MyViewController* myViewController; } - (id) initWithHost:(MyViewController*) host { self = [super init]; self.myViewController = host; self.theConnection = nil; return self; } // Make the connection - (void) connect: (NSString* url); // Cancel the connection - (void) cancel; // Delegate methods - (void) connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse*)response - (void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error - (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data - (void) connectionDidFinishLoading:(NSURLConnection*) connection
  • 13. Usage   // We are now in some ViewController class [URLConnection *myConn = [[URLConnection alloc] initWithHost: self]; [myConn connect:@"http://www.tamk.fi"];
  • 14. When  connec@on  is  finished   - (void) connectionDidFinishLoading:(NSURLConnection *) connection { unsigned char byteBuffer[[receivedData length]]; [receivedData getBytes:byteBuffer]; NSString *temp = [[NSString alloc] initWithBytes:byteBuffer length:[receivedData length] encoding:4]; // Do something with the data.. For example // make a call back method for the viewController [myViewController setThisTextToTextView: temp]; [temp release]; [connection release]; [receivedData release]; self.theConnection = nil; }