如何在一定时间后触发动作?

时间:2011-07-18 05:49:45

标签: iphone objective-c

在我的应用程序中,如果网络连接在几秒钟后过慢,我想显示错误消息。我应该如何实现这个? 这是代码:

-(void)setProjectID:(NSString *)newProject {
    [self willChangeValueForKey:@"projectID"];
    [projectID release];
    projectID = [newProject copy];
    [self didChangeValueForKey:@"projectID"];

    // Since we have an ID, now we need to load it
    NSInvocation *returnInvocation = [NSInvocation invocationWithMethodSignature:
                                      [Detail instanceMethodSignatureForSelector:@selector(configureView:)]];
    [returnInvocation setTarget:self];
    [returnInvocation setSelector:@selector(configureView:)];
    [returnInvocation retainArguments];

    fetch = [[WBWDocumentFetcher alloc] init];
    [fetch retrieveDocument:[NSURL wb_URLForTabType:PROJECT_DETAILS inProject:projectID] returnBy:returnInvocation];
}
-(void)configureView:(NSDictionary *)serverResult 
{
}

谢谢,

2 个答案:

答案 0 :(得分:1)

您想使用performSelector:afterDelay:或可能performSelector:withObject:afterDelay:

然后,在调用方法的开头,检查页面是否已加载。如果没有,则显示UIAlertView并取消加载。

答案 1 :(得分:0)

如果您使用NSURLRequest请求服务器而不是使用以下代码来判断超时。

//In this you can set timeoutinterval for request
NSURLRequest* request = [NSURLRequest requestWithURL:yourURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

//If request is failing for time out reason you can check that and alert user accordingly.
-(void)connectionFailed:(NSError *)error
{
UIAlertView *objAlert = [[UIAlertView alloc] init]; 
[objAlert setTitle:@"Internet Connection"];
[objAlert addButtonWithTitle:@"Ok"];
if([error code] == -1001 || [[error localizedDescription] isEqualToString:@"timed out"]){
        [objAlert setMessage:@"Request Timed Out."];
        [objAlert show];
    }
}