// ViewController.m
// NSURLConnection
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
NSString *parameter = [NSString stringWithFormat:@"DeviceUDID=%@",[[[UIDevice currentDevice] identifierForVendor] UUIDString]];
commonClass *conn=[[commonClass alloc]init];
conn.delegate=self;
conn.postDataIDREturn = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[conn connectionWithURL:@"https://YOUR URL/"];
}
-(void)connectionSucceed:(NSData *)data
{
//calling the Loading Action method
NSError *error = nil;
NSDictionary *dictionarys = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
}
-(void)connectionFailed:(NSError *)error
{
NSLog(@"Error: %@",error);
}
@end
Custom Class:
// commonClass.h
#import <Foundation/Foundation.h>
#import <UIkit/UIKit.h>
@protocol connectionDelegate <NSObject>
-(void)connectionSucceed:(NSData *)data;
-(void)connectionFailed:(NSError *)error;
@end
@interface commonClass : NSObject
{
id<connectionDelegate> delegate;
NSMutableData *receivedData;
}
@property(nonatomic, retain) id<connectionDelegate> delegate;
@property(nonatomic, retain) NSMutableData *receivedData;
@property(nonatomic,retain) NSData *postDataIDREturn;
- (void)connectionWithURL:(NSString *)URL;
@end
// commonClass.m
#import "commonClass.h"
@implementation commonClass
@synthesize delegate, receivedData,postDataIDREturn;
- (void)connectionWithURL:(NSString *)URL
{
NSURL *url = [NSURL URLWithString:URL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:postDataIDREturn];
theRequest.timeoutInterval = 150;
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( connection )
{
self.receivedData = [[NSMutableData alloc] init];
}else
{
NSLog(@"Connection Failed!");
}}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self.delegate connectionSucceed:self.receivedData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self.delegate connectionFailed:error];
}
@end
No comments:
Post a Comment