对HTTP Post请求进行排序

时间:2014-01-15 19:19:51

标签: php objective-c http-post

我绝对会失去理智。我有两个按顺序排列的http post调用。第一个成功返回。当发生这种情况时,执行第二次调用,但它永远不会返回。我检查了一切。我将我的php脚本归结为不带参数的地方,只返回一个字符串。但它仍然没有回来。我不允许像这样对HTTP请求进行排序吗?或者我只是错过了一些愚蠢的东西?

我已经尝试了所有我能想到的东西,但我现在已经开始了。如果我无法解决这个问题,我的应用程序已经死了。强调帮助请求!!!

这是第一个电话。这个工作得很好:

NSString *post = [NSString stringWithFormat:@"&id=%@&password=%@",
                  [[NSUserDefaults standardUserDefaults] objectForKey:@"id"],
                  passwordTextField.text];

NSString *script = @"verifyPassword.php";

MyDownloader *d = [[MyDownloader alloc] initWithPost:post script:script];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(verificationResultsReceived:)
                                             name:@"connectionFinished"
                                           object:d];

[d.connection start];

这是该通话的通知方法。

- (void) verificationResultsReceived: (NSNotification *) n
{
    MyDownloader *d = [n object];

    [self.activityIndicator stopAnimating];

    if ([n userInfo]) {
        NSLog(@"information retrieval failed");
    } else {

        NSArray *response = [NSJSONSerialization JSONObjectWithData:d.receivedData options:kNilOptions error:nil];

        if (response) {
            if ([[response valueForKey:@"result"] isEqualToString:@"success"]) {
                // password is verified - OK to update settings
                [self.activityIndicator startAnimating];

                NSString *post = @"";
                NSString *script = @"test.php";
                MyDownloader *d1 = [[MyDownloader alloc] initWithPost:post script:script];

                [[NSNotificationCenter defaultCenter] addObserver:self
                                                         selector:@selector(updateResultsReceived:)
                                                             name:@"connection2Finished"
                                                           object:d1];
                    NSLog(@"I got this far!");
                [d1.connection start];

            } else {
                // incorrect password entered - notify user and halt
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Incorrect Password"
                                                                message:@"Invalid password entered. Please try again."
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];

                [alert show];
            }

        } else {
            NSLog(@"The server has responded with something other than a JSON formatted object");
        }
    }

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"connectionFinished"
                                                  object:d];
}

这是下一个通知监视器。它永远不会到这里!为什么????

- (void) updateResultsReceived: (NSNotification *) n
{
    NSLog(@"But why don't I see this?");

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"connection2Finished"
                                                  object:d];
}

如果有帮助,这里是MyDownloader类:

- (id) initWithPost: (NSString *)post
            script : (NSString *)script
{
    self = [super init];

    if (self) {
        self->_mutableReceivedData = [NSMutableData new];

        //Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        //You need to send the actual length of your data. Calculate the length of the post string.
        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

        //Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string.
        //Create URLRequest object and initialize it.
        self.request = [[NSMutableURLRequest alloc] init];

        // make a string with the url
        NSString *url = [@"http://www.mySite.com/" stringByAppendingString:script];

        // Set the Url for which your going to send the data to that request.
        [self.request setURL:[NSURL URLWithString:url]];

        //Now, set HTTP method (POST or GET).
        [self.request setHTTPMethod:@"POST"];

        //Set HTTP header field with length of the post data.
        [self.request setValue:postLength forHTTPHeaderField:@"Content-Length"];

        //Also set the Encoded value for HTTP header Field.
        [self.request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

        // Set the HTTPBody of the urlrequest with postData.
        [self.request setHTTPBody:postData];

        self->_connection =
        [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];

    }

    return self;
}

- (void) connectionDidFinishLoading:(NSURLConnection *) connection
{
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"connectionFinished" object:self];
}
Thanks for any advice.

1 个答案:

答案 0 :(得分:0)

不确定你在MyDownloader课程中做了什么,但让我猜。您创建一个NSURLConnection实例并抓住发送通知的connectionDidFinishLoading

您必须记住的一件事是,当您使用initWithRequest创建连接时,它实际上已启动。

  

<强>讨论
  这相当于调用initWithRequest:delegate:startImmediately:并将YES传递给startImmediately

因此,由于连接已经开始,[d.connection start];可能无效。也许在你注册成观察员之前它已经回来了!

顺便说一句,工作者类(如下载程序)的首选模式是Singleton Pattern。也许你想要看一个类总是知道什么连接是活跃的。