使用sendAsynchronousRequest时显示“数据加载”:queue:completionHandler:

时间:2013-04-06 17:49:34

标签: ios networking delegates nsurlconnection objective-c-blocks

我正在使用此块方法从服务器加载我的数据......

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[myString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]
                                            cachePolicy:NSURLRequestUseProtocolCachePolicy
                                        timeoutInterval:60.0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
 sendAsynchronousRequest:urlRequest
 queue:queue
 completionHandler: ^( NSURLResponse *response,
                      NSData *data,
                      NSError *error)
 {
     [[mySingleton dictionaryUserDetail] removeAllObjects];
     [[mySingleton arrayUserDetail] removeAllObjects];

     if ([data length] > 0 && error == nil) // no error and received data back
     {
         NSError* error;
         NSDictionary *myDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
         [mySingleton setDictionaryUserDetail:[myDic mutableCopy]];

         NSArray *myArray = [myDic objectForKey:@"searchResults"];
         [mySingleton setArrayUserDetail:[myArray mutableCopy]];

         dispatch_async(dispatch_get_main_queue(), ^{
             [self userDetailComplete];
         });
     } else if
         ([data length] == 0 && error == nil) // no error and did not receive data back
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             [self serverError];
         });
     } else if
         (error != nil) // error
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             [self serverError];
         });
     }
 }];

我希望能够向用户显示进度条而不仅仅是微调器。如果我使用代表,我认为我可以使用NSURLConnectionDelegate

connection:didReceiveData:

但我不知道怎么用块来做这件事。任何人都有天才的见解吗?

1 个答案:

答案 0 :(得分:3)

如果要显示显示实际下载进度的进度条,则必须使用NSURLConnection的基于委托的方法。 sendAsynchronousRequestsendSynchronousRequest没有为此提供方法。