gpt4 book ai didi

ios - NSURLConnection 顺序错误

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:09:16 25 4
gpt4 key购买 nike

我有一个 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 在第一个之前 运行。所以它会尝试转到我在登录时之前 下载数据的页面,因此它(显然)返回“您未登录”错误。如何依次安排它们?

最佳答案

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

最快和最简单的答案是简单地将对第二个请求的调用放在第一个请求的完成 block ,而不是在它之后。除非第一个无论如何都成功了,否则你不想做第二个。

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

- (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");
}];

现在,更改那些 successHandlerfailureHandler block 参数以包含您需要传回的任何数据,但希望它能说明这个想法。保持您的方法简短而紧凑,并使用完成 block 参数来指定异步方法在完成时应该做什么。

关于ios - NSURLConnection 顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22573458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com