如何访问值表单completionHandler并将其传递给另一个视图IOS

时间:2014-05-18 20:32:07

标签: ios objective-c handler

我试图从这个方法返回String我有两个类

第一个用于UI,它有两个输入文本用户和传递,我也有提交按钮,另一个只做以下方法。

我试图将字符串从其他类返回到此类并在alert中显示字符串。

#import "LoginPage.h"

@implementation LoginPage

-(NSString *)responsData:(NSString *)loginUrl input1:(NSString *)username input2:(NSString *)password
{

    NSString *urlAsString = loginUrl;
    NSString*test;


    inUsername = username;
    inPassword = password;

    NSURL *url = [NSURL URLWithString:urlAsString];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setTimeoutInterval:30.0f];
    [urlRequest setHTTPMethod:@"POST"];

    // Setting Username and password
    NSString *body = [NSString stringWithFormat:@"sended=yes&username=%@&password=%@",username,password];

    [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:queue
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil){ NSString *html =
             [[NSString alloc] initWithData:data
                                   encoding:NSUTF8StringEncoding];
            // NSLog(@"%@", html);
             self.lastValue = [NSString stringWithFormat:@"%@",html];
         }
         else if ([data length] == 0 && error == nil){
             //NSLog(@"Nothing was downloaded.");
              self.lastValue = [NSString stringWithFormat:@"No thing was downloaded"];
         }
         else if (error != nil){
           //  NSLog(@"Error happened = %@", error);
              self.lastValue = [NSString stringWithFormat:@"%@",error];
         } }];


    NSLog(@"%@",self.lastValue);
    return  self.lastValue;
}

// Do any additional setup after loading the view, typically from a nib.



@end

我想在另一个视图中使用此功能(我已经包含了此文件的标题),但我无法解决此问题>

另一种观点

- (IBAction)submit:(id)sender {
     LoginPage * login = [[LoginPage alloc]init];
   NSString * dataRe;
    dataRe =  [login responsData:@"http://fahads-macbook-pro.local/ios/post.php" input1:@"admin" input2:@"1234"];
    NSLog(@"%@",login.lastValue);
    if (dataRe != nil) {
        UIAlertView * alert =[[UIAlertView alloc]
        initWithTitle:@"Hello Fahad"
          message:[NSString stringWithFormat:@"%@",dataRe] delegate:self cancelButtonTitle:@"Okay ! " otherButtonTitles:nil, nil];
        [alert show];
    }


}

再次感谢您

2 个答案:

答案 0 :(得分:0)

当您在另一个视图上调用该功能时,它会向网络发送异步请求。 所以当你这样做时:

return self.lastValue;

lastValue 仍为空或使用之前的值,因为仍需要调用competionHandler completionHandler的代码,只是传递给函数的代码的和平,将在适当的时刻调用。所以函数到达最后的位置return

当调用完成处理程序块时(因为请求已生成响应),您可以分配值:

self.lastValue = [NSString stringWithFormat:@"%@",html];

现在lastValue是对的。

因此,您的功能不应该返回 NSString,但应该返回 void。 要将字符串传递给其他控制器,您应该使用 delegation pattern

这是一个非常快速的例子

<强> SecondViewController.h

@protocol SecondViewControllerDelegate <NSObject>

- (void)lastValueDidUpdate:(NSString *)lastValue;

@end

@interface SecondViewController : UIViewController

@property (weak, nonatomic) id<SecondViewControllerDelegate>delegate;

@end

<强> SecondViewController.m

#import "SecondViewController.h"
@implementation SecondViewController

-(NSString *)responsData:(NSString *)loginUrl input1:(NSString *)username input2:(NSString *)password
{

    NSString *urlAsString = loginUrl;
    NSString*test;


    inUsername = username;
    inPassword = password;

    NSURL *url = [NSURL URLWithString:urlAsString];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setTimeoutInterval:30.0f];
    [urlRequest setHTTPMethod:@"POST"];

    // Setting Username and password
    NSString *body = [NSString stringWithFormat:@"sended=yes&username=%@&password=%@",username,password];

    [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    __weak typeof (self) weakSelf = self;

    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:queue
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil){ NSString *html =
             [[NSString alloc] initWithData:data
                                   encoding:NSUTF8StringEncoding];
             // NSLog(@"%@", html);
             weakSelf.lastValue = [NSString stringWithFormat:@"%@",html];
         }
         else if ([data length] == 0 && error == nil){
             //NSLog(@"Nothing was downloaded.");
             weakSelf.lastValue = [NSString stringWithFormat:@"No thing was downloaded"];
         }
         else if (error != nil){
             //  NSLog(@"Error happened = %@", error);
             weakSelf.lastValue = [NSString stringWithFormat:@"%@",error];
         }

         [weakSelf.delegate lastValueDidUpdate:weakSelf.lastValue];

     }];
}


@end

<强> FirstViewController.h

#import "SecondViewController.h"

@interface FirstViewController : UIViewController <SecondViewControllerDelegate>

@property (strong, nonatomic) SecondViewController *secondViewController;

@end

FirstViewController.m

#import "FirstViewController.h"

@implementation FirstViewController

- (void)viewDidLoad {
    //your code

    [_secondViewController setDelegate:self];

    //your code
}

//your code

@end

请注意,我使用弱引用自我,否则您可以创建保留周期。

答案 1 :(得分:0)

在第一个类中定义一个方法,即UI类,如:

- (void)callFromBlock:(NSString*)stringFromResponse
{
    if (stringFromResponse != nil) {
        UIAlertView * alert =[[UIAlertView alloc]
                              initWithTitle:@"Hello Fahad"
                              message:[NSString stringWithFormat:@"%@",stringFromResponse] delegate:self cancelButtonTitle:@"Okay ! " otherButtonTitles:nil, nil];
        [alert show];
    }


}

并且提交方法应如下所示:

   - (IBAction)submit:(id)sender {
         LoginPage * login = [[LoginPage alloc]init];
       NSString * dataRe;
        dataRe =  [login responsData:@"http://fahads-macbook-pro.local/ios/post.php" input1:@"admin" input2:@"1234"];

}

现在取代块中的return语句,在获得响应时从块中调用 callFromBlock 方法,并将字符串传递给您尝试返回的此方法。

希望它有所帮助。