【问题标题】:How to show an activity indicator bar while waiting for response from a server?如何在等待服务器响应时显示活动指示条?
【发布时间】:2014-06-05 04:56:37
【问题描述】:

全部!首先,我已经看到了所有此类问题,但仍然感到困惑,这就是我问的原因。 我有一个“翻译”按钮。当我按下按钮时,它会向服务器发送请求并得到响应。因此,在等待答案时,我需要显示活动指示条。我尝试了一些代码,但没有任何效果。有人可以帮我吗?这是我的代码。我的活动指标是 activityInd。

-(IBAction)translate
{
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:[[self textView1] text], @"SourceText",@"8a^{F4v", @"CheckCode",@"0",@"TranslateDirection",@"1",@"SubjectBase", nil];
NSError *error=nil;
    NSData *result=[NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSURL *url=[NSURL URLWithString:@"http://fake.com/notRealUrl"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];


    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:result];

    NSURLResponse *response=nil;

    NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSUTF8StringEncoding ];

    NSString *str=theReply;
    str= [str substringWithRange:NSMakeRange(51, str.length - 51 - 2)];

    NSString *result2=[str stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@""];
    _textView.text=result2;
}

谢谢大家!我找到了一种使用异步请求的方法。 现在一切正常。

【问题讨论】:

    标签: ios ios7 activity-indicator


    【解决方案1】:

    您正在发出同步请求。所以它将在主线程上执行。这将使您的主线程忙碌,并且您的 UI 在此期间不会更改。使通信请求异步,您的 UI 将使用活动视图进行更新。

    【讨论】:

      【解决方案2】:

      试试这个:

         //set ivar in your view controller
         UIActivityIndicatorView * spinner;
      
         //alloc init it  in the viewdidload
          spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
          [self addSubview:spinner];
          [spinner setFrame:CGRectMake(0, 0, 100, 100)];
          [spinner setCenter:CGPointMake(self.center.x, 150)];
          spinner.transform = CGAffineTransformMakeScale(2, 2);
          [spinner setColor:[UIColor darkGrayColor]];
      

      在请求之前添加以下代码:

      [self bringSubviewToFront:spinner];
      [spinner startAnimating];
      

      完成后:

      [spinner stopAnimating];
      

      【讨论】:

        【解决方案3】:

        您只能在主线程上更改 UI。

        -(void)translate
        {
        //maybe your app is running on main thread so Start Spinner in main thread.
        UIActivityIndicatorView * spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        
        [spinner setCenter:self.view.center];
        [self.view addSubview:spinner];
        [self.view bringSubviewToFront:spinner];
        [spinner startAnimating];
        
        // Create this temporary block.
        [self callService:^(NSData *data, BOOL success)
        {
            /*--- When you get response execute code in main thread and stop spinner. ---*/
            dispatch_async(dispatch_get_main_queue(), 
            ^{
                // now app is in main thread so stop animate.
                [spinner stopAnimating];
                if (success)
                {
                    NSString *theReply = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding: NSUTF8StringEncoding ];
                    //do what you want.
        
                }
            });
        }];
        }
        
        -(void)callService:(void(^)(NSData *data,BOOL success))block
        {
        //we are calling Synchronous service in background thread.
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        
            NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:@"", @"SourceText",@"8a^{F4v", @"CheckCode",@"0",@"TranslateDirection",@"1",@"SubjectBase", nil];
            NSError *error=nil;
            NSData *result=[NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
            NSURL *url=[NSURL URLWithString:@"http://fake.com/notRealUrl"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
        
            [request setHTTPMethod:@"POST"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:result];
        
            NSURLResponse *response=nil;
        
            NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        
            // When we got response we check that we got data or not . if we get data then calling this block again.
            if (POSTReply)
                block(POSTReply,YES);
            else
                block(nil,NO);
        });
        }
        

        也许这会对你有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-10
          • 2018-11-28
          • 2019-10-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多