简体   繁体   English

从另一个类调用自定义和委托方法

[英]calling custom and delegate method from another class

I am a beginner in objective c. 我是目标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. 我有两个类Connectivity和SignInViewController,我想要的是在另一个类的一次调用中调用一个类中定义的方法。 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. 我知道,我可以通过protocoldelegation来实现它,但是仍然想知道是否有任何简单的方法可以做到这一点。 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. 当调试代码,我可以看到的是,控制将要在SigninViewController执行后+ (void)connectWithURL:(NSURL *)URL withData:(NSString *)postedData方法。 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 . 但是我想要的是先执行连接类的所有方法(下面定义的委托方法),然后该控件应返回到SigninViewController Hope, i asked it clearly. 希望,我问清楚了。

`// connectivity.h `// Connectivity.h

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

//connectivity.m //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) //我正在(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`
- (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. 这不是一个完美的答案,但是可以通过在Connectivity.m类中声明一个委托来进行匹配。 Implement the methods of delegates in SignInViewController, by this way you can achieve this. 在SignInViewController中实现委托的方法,通过这种方式可以实现。 Do not for get to assign the delegate to SignInViewController. 请勿将委托分配给SignInViewController。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM