【问题标题】:NSURLConnection delegates not being called even when run on main threadNSURLConnection 委托即使在主线程上运行也不会被调用
【发布时间】:2013-06-12 05:42:36
【问题描述】:

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

-(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
}

【问题讨论】:

    标签: objective-c xcode delegates nsurlconnection


    【解决方案1】:

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

    【讨论】:

    • 是的 ;) +1 @Spenciefy 您需要证明您在每个委托方法中使用的连接。
    • 谢谢。不太确定我在想什么 2. 现在似乎可以工作了。
    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多