首次尝试后续尝试的NSURLConnection超时工作

时间:2013-01-25 00:12:36

标签: ios nsurlconnection

我遇到与我正在调用的REST服务的NSURL连接有问题。

问题是它可以通过浏览器或使用RESTClient进行检查,但在设备(iOS5,iOS6,仿真器)上有时它不会第一次工作。超时后,它随后会工作。

这真的让我疯狂。

调用它的main函数通过GCD调用,然后处理主线程上的结果代码。 200 =验证成功,!200 =当然失败(超时等,通过返回的整数处理)。

如前所述,问题是第一次调用它只是超时,没有返回任何内容。如果进行得足够快,后续调用往往会起作用,但如果让它静置一两分钟,则连接会在尝试访问时超时。

我无法通过浏览器或RESTClient复制此行为。就像iOS一样。我要带香蕉。

这是进行调用的主要功能

-(int)AuthUser:(ApiUser*)user{

// Authenticates the Users
// Build the URL
NSString *accessAppendix = @"/api/user/authenticate";
NSString *accessURL = [NSString stringWithFormat:@"%@%@",self.apiParameters.rootServer, accessAppendix];
NSURL *accessJSONURL= [[NSURL alloc] initWithString:accessURL];

// Setup HTTP Request Headers
NSMutableURLRequest *urlRequest = [self BuildApiUrlRequest:accessJSONURL];

// Setup dictionaries
// For posting login data

NSDictionary *Application = [[NSDictionary alloc]
                             initWithObjectsAndKeys:@"XXXXXXXXX",
                             @"Application", nil];

NSDictionary *User = [[NSDictionary alloc]
                      initWithObjectsAndKeys:
                      user.UserId,@"UserId",
                      user.Password,@"Password",
                      user.Type,@"Type",nil];

NSDictionary *Office = [[NSDictionary alloc]
                        initWithObjectsAndKeys:
                        user.office,@"Number", nil];

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                            User,@"User",
                            Application,@"Application",
                            Office,@"Office",nil];

// Setup Error handler
NSError *jError;

// Serialise JSON String
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONReadingMutableContainers error:&jError];

// attach to HTTP Body
[urlRequest setHTTPBody:jsonData];

// Log URL Body
NSLog(@"Data %@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSLog(@"Data length: %u",[jsonData length]);    

// set Content Length
// This doesn't seem to be required really
NSString *msgLength = [NSString stringWithFormat:@"%d", [jsonData length]];
[urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];

NSURLResponse* response;
NSError* error = nil;

// fire Request        
NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

NSString *responseBody = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(@"URL Response: %@",responseBody);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"HttpResponse: %d",[httpResponse statusCode]);

return [httpResponse statusCode];
}

这是Build API URL Request函数。

// Builds API URL Request
-(NSMutableURLRequest*) BuildApiUrlRequest:(NSURL*)jURL
{
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:jURL];
[urlRequest setHTTPMethod:@"POST"];
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", self.apiParameters.rootCredentials];
[urlRequest addValue:authHeader forHTTPHeaderField:@"Authorization"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setTimeoutInterval:10];
urlRequest.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

return urlRequest;
}

思考?它只返回响应代码0并在失败时超时。当它工作时,它工作得很好,并返回200。

UPDATE :这是从View Controller调用的方式(按下按钮):

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        int returnNumber = [app.pApi AuthUser:newUser];

        dispatch_async( dispatch_get_main_queue(), ^{
            [self loginResultHandler:returnNumber];
        });
    });

以这种方式完成,因为我想将API类从控制类中分离出来。

0 个答案:

没有答案