Header Ads

URL Loading System - Objective C

URL Loading is useful in  accessing URL, i.e. the items from the internet. It is provided with the help of the following classes:
  • NSMutableURLRequest
  • NSURLConnection
  • NSURLCache
  • NSURLAuthenticationChallenge
  • NSURLCredential
  • NSURLProtectionSpace
  • NSURLResponse
  • NSURLDownload
  • NSURLSession
Here is a simple example for url loading. This cannot be run on command line. We need to create Cocoa Application.

This can be done by selecting New in XCode, then Project and select Cocoa Application under the OS X application section of the window that appears.

Complete the sequence of steps by clicking next and you will be asked to provide a project name and you can give it a name.

The appdelegate.h file will be as follows:

#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject < NSApplicationDelegate>
 
@property (assign) IBOutlet NSWindow *window;

@end

update the AppDelegate.m file to following:

#import "AppDelegate.h"
@interface SampleClass : NSObject <NSURLConnectionDelegate>
{
           NSMutableData *_responseData;
}
  - (void)initiateURLConnection;

@end

@implementation SampleClass
 -(void)initiateURLConnection
{
           //create the request
          NSURLRequest  *request = [NSURLRequest requestWithURL : 
                  [NSURL URLWithString : @"http://www.soltrickspro.blogspot.com"]];
    
          //create url connection and fire request
         NSURLConnection *conn = [[NSURLConnection alloc ] initWithRequest : request 
          delegate : self]
        [conn start];
}
#pragma mark NSURLConnection Delegate Methods

- (void) connection : (NSURLConnection *)connection didReceiveRespone : 
 (NSURLResponse *) response {
 
   _responseData = [[NSMutableData alloc]init];
}
 
 
- (void)connection : (NSURLConnection *) connection didReceiveData : 
  (NSData *)data {
  
    [_responseData appendData : data];
}
 
-(NSCachedURLResponse *) connection : (NSURLConnection *) connection 
      willResponse : (NSCachedURLResponse *)cachedResponse {
    
   return nil;
}
 
- (void)connectionDidFinishLoading : (NSURLConnection *)connection {
 
         NSLog(@"%@", [[NSString alloc]initWithData : _responseData 
                      encoding : NSUTF8StringEncoding]);
}
 
- (void)connection : (NSURLConnection *)connection didFailWithError : (NSError *)error
 {
 
}
 
@end
 
 
@implementation AppDelegate
 
 - (void)applicationDidFinishLaunching : (NSNotification *)aNotification
 {
      SampleClass *sampleClass = [[SampleClass alloc] init];
      [sampleClass initiateURLConnection ];
}
@end
 



In the above program , we have created a simple URL connection that takes the time in JSON format and display the time.

 

  NSData *data = [fileManager contentsAtPath :@"Path"];

No comments:

Powered by Blogger.