活动指示器在加载结束时开始

时间:2010-03-06 14:54:12

标签: iphone xcode

我的代码出了什么问题?

我想在view1.nib开始加载时启动微调器指示器。 所以我把[spinner startAnimating]; in - (void)viewDidLoad。 但它会得到那个url然后启动微调器指示器......

- (void)viewDidLoad {








[spinner startAnimating];

NSURL *originalUrl=[NSURL URLWithString:@"http://example.com/"];
NSData *data=nil;  
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:originalUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
NSURLResponse *response;
NSError *error;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


NSURL *LastURL=[response URL];


NSLog(@"%@",LastURL);



[backr,backrm,downloadr  setEnabled:FALSE];

backr.hidden=YES;
backrm.hidden=YES;
downloadr.hidden=YES;
[self nextr:0];
[super viewDidLoad];

}

2 个答案:

答案 0 :(得分:1)

您正在主线程上同步下载数据,因此UI将一直挂起,直到操作完成。这就是为什么你的旋转仅在完成时显示。

在后台线程中运行下载,或使用NSURLConnection的异步方法。

答案 1 :(得分:1)

您的问题是使用sendSynchronousRequest阻止主线程。 在下载数据时,您的线程会阻塞,因此您的动画也是如此,并且在请求完成后动画继续。

我应该使用connectionWithRequest:delegate:或initWithRequest:delegate:方法并将委托设置为self。 您可以在此处找到更多信息:Using NSURLConnection


修改

示例:

在您的界面中定义它:

@interface YourInterface {
@private
   NSMutableData *receivedData;
}

然后在你的控制器中进入viewDidLoad:

// your previous definition of your NSMutableRequest

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if (theConnection) {
    // Create the NSMutableData that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    receivedData=[[NSMutableData data] retain];
} else {
    // inform the user that the download could not be made
}

再次在你的控制器中完成这些方法:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // release the connection, and the data object
    [connection release];

    // receivedData is declared as a method instance elsewhere
    [receivedData release];

    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    // release the connection, and the data object
    [connection release];
    [receivedData release];
}