1

我知道这种问题已经被问过很多次了,但他们都指向说连接必须在不同的线程上。

-(void)distanceMatrix{

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:distanceMatrixURL]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10];

connection2 = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];

[connection2 scheduleInRunLoop:[NSRunLoop mainRunLoop]
                      forMode:NSDefaultRunLoopMode];

NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));
[connection2 start];

if (connection2)
{
    responseData2 = [NSMutableData data];
    connectionIsActive = YES;    
} else {
    NSLog(@"connection failed");
}
}

- (void)connection2:(NSURLConnection *)connection2 didReceiveResponse:(NSURLResponse *)response
{NSLog(@"recieved response");
[responseData2 setLength:0];

}

- (void)connection2:(NSURLConnection *)connection2 didReceiveData:(NSData *)data
{
[responseData2 appendData:data];

}

- (void)connection2:(NSURLConnection *)connection2 didFailWithError:(NSError *)error
{
connectionIsActive = NO;
    NSLog(@"failed!!");
}

- (void)connection2DidFinishLoading:(NSURLConnection *)conn
{  

connectionIsActive          = NO;
SBJsonParser *json          = [[SBJsonParser alloc] init];
NSString *responseString    = [[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding];
NSError *jsonError          = nil;

NSDictionary *parsedJSON    = [json objectWithString:responseString error:&jsonError];

travelTime= [[[[parsedJSON valueForKey:@"rows"] valueForKey:@"elements"] valueForKey:@"duration"] valueForKey:@"text"];

NSLog(@"traveltime = %@", travelTime);
}

当我记录它时,它说它在主线程上运行。Connection2 处于活动状态,但没有调用任何代表。

另外,这是我调用 distanceMatrix 方法的方式

-(id)initWithJsonResultDict:(NSDictionary *)jsonResultDict andUserCoordinates:    (CLLocationCoordinate2D)userCoords andTimeURL:(NSString*)timeURL
{
self.distanceMatrixURL = timeURL;
[self distanceMatrix];
//more code here for other purposes
}
4

1 回答 1

6

因为您已将 a 添加2到所有委托方法的名称中。这会更改方法签名,因此您没有实现正确的方法。删除2方法开头的所有- (void)connection2:,它应该可以工作。

于 2013-06-12T06:43:00.170 回答