0

I am a beginner in objective c. I have two classes Connectivity and SignInViewController, and what i want is to call the methods defined in a class on a single call from another class. I came to know that, i can achieve it through protocol or delegation, but still wondering if there would be any simple way to do this. when i debug the code, i can see that the control is going to the SigninViewController after executing the +(void)connectWithURL:(NSURL *)URL withData:(NSString *)postedData method. But what i want is to execute all the method(delegation methods defined below) of connectivity class first and after that control should go back to the SigninViewController. Hope, i asked it clearly.

`// connectivity.h

 #import<Foundation/Foundation.h>
@interface Connectivity : NSObject<NSURLConnectionDelegate, NSURLConnectionDelegate>
+(void)connectWithURL:(NSURL *)URL withData:(NSString *)postedData;
@end 

//connectivity.m

#import "Connectivity.h"
NSMutableData *_receivedData;
@implementation Connectivity
+(void)connectWithURL:(NSURL *)URL withData:(NSString *)postedData
{
//Create the Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSLog(@"posted url %@", URL);
//Create The Method "POST"
[request setHTTPMethod:@"POST"];
//header
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded"   forHTTPHeaderField:@"Content-Type"];

//Pass the String to the Server
NSString *postString = [NSString stringWithString:postedData];

//Check the Passed Value
NSLog(@"post string =%@", postedData);
//Convert the String to Data
NSData *data1 = [postedData dataUsingEncoding:NSUTF8StringEncoding];
//Apply the Data to the Body
[request setHTTPBody:data1];
//connection to the webserver

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];
[connection start];
}
#pragma mark NSURLConnection Delegate Methods

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

[_receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.

[_receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data

NSLog(@"Succeeded! Received %lul bytes of data",[_receivedData length]);
NSString *responeString = [[NSString alloc] initWithData:_receivedData
                                                encoding:NSUTF8StringEncoding];

connection = nil;
_receivedData = nil;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

connection = nil;
_receivedData = nil;

// inform the user

NSLog(@"Connection failed! Error - %@ %@",
      [error localizedDescription],
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
@end

//I am calling the method in (SignInViewController.m)

#import "SignInViewController.h"
#import "AlertMessageViewController.h"
#import "Connectivity.h"

@interface SignInViewController ()

@end

@implementation SignInViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)loginCustomUser
{

if([[self.emailTextField text] isEqualToString:@""] || [[self.passwordTextField text] isEqualToString:@""])
{
  [self presentViewController:[AlertMessageViewController alertWithTitle:@"Error" withMessage:@"Enter email and Password" preferredStyle:UIAlertControllerStyleAlert] animated:YES completion:nil];
}
else
{
NSString *data = [NSString stringWithFormat:@"{\"rqBody\":{\"emailId\":\"%@\",\"password\":\"%@\",\"userId\":\"%@\",\"idType\":\"%@\",\"firstName\":\"%@\",\"lastName\":\"%@\",\"contactNumber\":\"%@\",\"firstLineOfAddress\":\"%@\",\"localityName\":\"%@\",\"city\":\"%@\",\"state\":\"%@\",\"country\":\"%@\",\"roleType\":\"%@\",\"paymentProfile\":\"%@\",\"paymentDate\":\"%@\",\"registerationStatus\":\"%@\",\"loggedStatus\":\"%@\",\"lastLoggedInDate\":\"%@\",\"registerationDate\":\"%@\",\"profileStatus\":\"%@\"}}",[self.emailTextField text],[self.passwordTextField text],@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",nil];

    NSURL *mainUrl= [NSURL URLWithString:@"http://192.168.1.5:8080/referamaid/app/noauth/signin"];

    [Connectivity connectWithURL:mainUrl withData:data];

}
}
@end`
Kunal Kumar
  • 1,722
  • 1
  • 17
  • 32

1 Answers1

0
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

//      NSLog(@"%@",response);
//    NSLog(@"TAG== %d",  self.tag);

    NSDictionary *responseJson = [response JSONValue];

    NSError *error;

    JSONDecoder *jsonKitDecoder = [JSONDecoder decoderWithParseOptions:JKParseOptionValidFlags];

    NSDictionary *dictionary;
    if ([[jsonKitDecoder objectWithData:receivedData] valueForKey:@"d"])
    {
        dictionary = [[[jsonKitDecoder objectWithData:receivedData] valueForKey:@"d"] objectFromJSONString];
    }
    else
    {
        dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions | NSJSONReadingAllowFragments |NSJSONReadingMutableContainers error:&error];
    }

    //      NSLog(@"responseJson== %@",  [responseJson valueForKeyPath:@"data.WorkCell.label"]);

//    NSLog(@"%@",_delegate);

        if(_delegate){
            if ([_delegate respondsToSelector:@selector(requestFinished:withInfo:)]) {

                [_delegate requestFinished:self withInfo:dictionary];
                isRequest = FALSE;
            }
        }
    }

@protocol RequestDelegate <NSObject>

@optional
-(void)requestStarted:(Request *)request;
-(void)requestFailed:(Request *)request withError:(NSError *)error;

@required
-(void)requestFinished:(Request *)request withInfo:(NSDictionary *)info;

@end

Not perfect answer, but you can match by declaring a delegate in Connectivity.m class. Implement the methods of delegates in SignInViewController, by this way you can achieve this. Do not for get to assign the delegate to SignInViewController.

Arpit B Parekh
  • 1,932
  • 5
  • 36
  • 57