首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sendAsynchronousRequest的IOS问题

sendAsynchronousRequest的IOS问题
EN

Stack Overflow用户
提问于 2013-11-06 22:18:08
回答 2查看 915关注 0票数 3

我和[NSURLConnection sendAsynchronousRequest: queue: completionHandler:]有一些严重的问题。我使用rest代理登录和验证用户。下面显示了用于登录的下列内容:

代码语言:javascript
复制
    //Display the progress HUB
    [SVProgressHUD showWithStatus:@"Signing Up..." maskType:SVProgressHUDMaskTypeClear];

    NSError *error;
    [self setUserCredentials];

    //assign the parentView controller to the sender and email to the local class variables
    parentView = sender;
    userEmail = email;

    // create json object for a users session
    NSDictionary* session = [NSDictionary dictionaryWithObjectsAndKeys:
                             email, @"email",
                             password, @"password",
                             [NSDictionary dictionaryWithObjectsAndKeys:
                              [[UIDevice currentDevice] model], @"device",
                              [[UIDevice currentDevice] identifierForVendor].UUIDString, @"device_id",
                              @"APNS", @"push_to",
                              [[NSUserDefaults standardUserDefaults] stringForKey:@"push_id"], @"push_id",
                              nil],
                             @"mession",
                             nil];

    NSData *jsonSession = [NSJSONSerialization dataWithJSONObject:session options:NSJSONWritingPrettyPrinted error:&error];
    NSString *url = [NSString stringWithFormat:@"%@api/v1/messions.json", CoffeeURL];

    NSLog(@"URL: %@", url);

    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:30.0];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [jsonSession length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonSession];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

        NSLog(@"Length: %d", data.length);

        if (error == nil)
        {
            //if no error ocours set the user defualts and create the mession and log into the app
            NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *JSONResponse = [NSJSONSerialization JSONObjectWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error: &error];

            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

            NSLog(@"JSON: %@", JSONResponse);
            NSLog(@"Response: %d", httpResponse.statusCode);

            if (JSONResponse != nil && httpResponse.statusCode == 200)
            {
                [self setUserDefualts:password sessionToUse:JSONResponse deckController:viewDeck sender:sender];
            }

            [SVProgressHUD dismiss];
        }
        else
        {
            NSLog(@"Error: %@", error);

            //Dismiss progress HUB here and inform user that an internal error has occured
            [SVProgressHUD dismiss];
            NSString *errorString = @"Sorry, an error has occoured while connecting to the Coffee server.";
            UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [errorAlertView show];
        }
    }];

当我使用有效的用户凭据登录时,此代码正常工作。当我使用无效的凭据时,服务器会向iOS客户端发送一个401和一个空JSON对象。这将返回带有有效的非空响应对象的error = nil和状态代码401。由于某些原因,返回错误,响应为零:

代码语言:javascript
复制
Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed.
(NSURLErrorDomain error -1012.)" UserInfo=0x1cd53b50 
{NSErrorFailingURLKey=http://192.155.94.183/api/v1/messions.json, 
NSErrorFailingURLStringKey=http://192.155.94.183/api/v1/messions.json, 
NSUnderlyingError=0x1cdc2b10 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork
 error -1012.)"}

这使得我很难区分发送请求时发生的错误和服务器在用户凭据与后端不匹配时生成的401错误。当我尝试用以下方法创建和处理请求时:

代码语言:javascript
复制
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];

NSURLDelegate:

代码语言:javascript
复制
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Called Outside!");

    NSDictionary *jsonSession;
    NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
    NSLog(@"Succeeded! Received %d bytes of data", [responseData length]);
    recievedResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    NSError *err = nil;
    jsonSession = [NSJSONSerialization JSONObjectWithData:[recievedResponse dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

    if ([connection.originalRequest.URL isEqual:[NSURL URLWithString:[NSString stringWithFormat:@"%@api/v1/messions.json", CoffeeURL]]])
    {
        NSLog(@"Status: %d", httpResponse.statusCode);
        NSLog(@"JSON: %@", jsonSession);
        NSLog(@"Called Inside!");
    }
}

返回的响应有效,当用户输入无效凭据时,不会引发错误,状态代码等于401。为什么这对(void)connectionDidFinishLoading:(NSURLConnection *)connection起作用,而对[NSURLConnection sendAsynchronousRequest: queue: completionHandler:]不起作用?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-25 03:36:05

结果是我们后端服务器上的一个漏洞。有时,它会发送非常奇怪的响应代码,这些代码由iOS NSURLConnection库处理不当。在这种特殊情况下,它显示为域错误。

票数 0
EN

Stack Overflow用户

发布于 2013-11-06 22:35:33

当URL处理系统接收到error HTTP状态代码(即不是2xx)时,不要依赖于不生成错误。

相反,使用返回的response,它允许您访问HTTP代码(在运行时检查类并转换为NSHTTPURLResponse,这样您就可以访问statusCode)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19824008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档