Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 错误的连接顺序_Ios_Http_Post_Nsurlconnection - Fatal编程技术网

Ios 错误的连接顺序

Ios 错误的连接顺序,ios,http,post,nsurlconnection,Ios,Http,Post,Nsurlconnection,我有一个NSURLConnection(其中两个),它们以错误的顺序运行。 以下是我的方法: - (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password { NSURL *url = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"]; //Create and s

我有一个NSURLConnection(其中两个),它们以错误的顺序运行。
以下是我的方法:

- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password {

    NSURL *url = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];

    //Create and send request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    [request setHTTPMethod:@"POST"];

    NSString *postString = [NSString stringWithFormat:@"Pin=%@&Password=%@",
                            [self percentEscapeString:pin],
                            [self percentEscapeString:password]];
    NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postBody];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         // do whatever with the data...and errors
         if ([data length] > 0 && error == nil) {
             NSError *parseError;
             NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
             if (responseJSON) {
                 // the response was JSON and we successfully decoded it

                 NSLog(@"Response was = %@", responseJSON);
             } else {
                 // the response was not JSON, so let's see what it was so we can diagnose the issue

                 NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                 NSLog(@"Response was not JSON (from login), it was = %@", loggedInPage);
             }
         }
         else {
             NSLog(@"error: %@", error);
         }
     }];


    //Now redirect to assignments page

    NSURL *homeURL = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
    NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
    [request setHTTPMethod:@"POST"];

    [NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError)
     {
         // do whatever with the data...and errors
         if ([homeData length] > 0 && homeError == nil) {
             NSError *parseError;
             NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
             if (responseJSON) {
                 // the response was JSON and we successfully decoded it

                 NSLog(@"Response was = %@", responseJSON);
             } else {
                 // the response was not JSON, so let's see what it was so we can diagnose the issue

                 NSString *homePage = [[NSString alloc] initWithData:homeData encoding:NSUTF8StringEncoding];
                 NSLog(@"Response was not JSON (from home), it was = %@", homePage);
             }
         }
         else {
             NSLog(@"error: %@", homeError);
         }
     }];

}

- (NSString *)percentEscapeString:(NSString *)string
{
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)string,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
因此,添加到
[NSOperationQueue mainQueue]
的是两个
NSURLConnection
。我的输出显示,第二个
NSURLConnection
在第一个之前运行。因此,它尝试在我登录之前转到我下载数据的页面,因此它(显然)返回一个“您未登录”错误。
我如何一个接一个地安排它们呢?

您可以查看下面的链接吗。它是强制一个操作等待另一个操作


希望这能有所帮助。

我想您已经意识到,问题是您正在执行异步网络请求(这很好;您不想阻塞主队列),因此无法保证它们完成的顺序

最快、最简单的答案是将对第二个请求的调用放在第一个请求的完成块内,而不是放在它之后。除非第一次成功,否则你不想做第二次

为了避免代码变得笨拙,请将登录与主页请求分开。您可以使用异步方法中常见的完成块模式。您可以向
loginToMistarWithPin
添加一个参数,指定请求完成时应执行的操作。您可能有一个成功的完成块处理程序,一个失败的完成块处理程序:

- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password success:(void (^)(void))successHandler failure:(void (^)(void))failureHandler {

    NSURL *url = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];

    //Create and send request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    [request setHTTPMethod:@"POST"];

    NSString *postString = [NSString stringWithFormat:@"Pin=%@&Password=%@",
                            [self percentEscapeString:pin],
                            [self percentEscapeString:password]];
    NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postBody];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         // do whatever with the data...and errors
         if ([data length] > 0 && error == nil) {
             NSError *parseError;
             NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
             if (responseJSON) {
                 // the response was JSON and we successfully decoded it

                 NSLog(@"Response was = %@", responseJSON);

                 // assuming you validated that everything was successful, call the success block

                 if (successHandler)
                     successHandler();
             } else {
                 // the response was not JSON, so let's see what it was so we can diagnose the issue

                 NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                 NSLog(@"Response was not JSON (from login), it was = %@", loggedInPage);

                 if (failureHandler)
                     failureHandler();
             }
         }
         else {
             NSLog(@"error: %@", error);

             if (failureHandler)
                 failureHandler();
         }
     }];
}

- (void)requestMainPage {

    //Now redirect to assignments page

    NSURL *homeURL = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
    NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
    [requestHome setHTTPMethod:@"GET"]; // this looks like GET request, not POST

    [NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError)
     {
         // do whatever with the data...and errors
         if ([homeData length] > 0 && homeError == nil) {
             NSError *parseError;
             NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
             if (responseJSON) {
                 // the response was JSON and we successfully decoded it

                 NSLog(@"Response was = %@", responseJSON);
             } else {
                 // the response was not JSON, so let's see what it was so we can diagnose the issue

                 NSString *homePage = [[NSString alloc] initWithData:homeData encoding:NSUTF8StringEncoding];
                 NSLog(@"Response was not JSON (from home), it was = %@", homePage);
             }
         }
         else {
             NSLog(@"error: %@", homeError);
         }
     }];

}
然后,当您想要登录时,您可以执行以下操作:

[self loginToMistarWithPin:@"1234" password:@"pass" success:^{
    [self requestMainPage];
} failure:^{
    NSLog(@"login failed");
}];

现在,将那些
successHandler
failureHandler
块参数更改为包含需要传回的任何数据,但希望它能说明这一点。保持方法简短紧凑,并使用完成块参数指定异步方法完成时应执行的操作。

它可能正在工作,但不确定。如何下载
HTML的内容https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage
从区块内部?我试着从
发送异步请求
打印
家庭数据
,但没有给我任何帮助。很抱歉,我没有实现你的更改(因为我的白痴),它工作得很好,非常感谢。现在我要在成功块中添加另一个成功块,这是明智的还是我应该用其他方式?因为现在我想
将一些数据发布到
PortalMainPage
@AndrewSB,只要您希望调用方法的代码能够指定异步请求成功(或不成功)完成时应调用的代码块,就可以使用该完成块模式。所以,底线是,在任何合适的地方都可以随意使用它。