首页 > 解决方案 > 在objective-c中从api获得响应后如何显示警报控制器?

问题描述

我有一个发布HTTP数据的方法,在得到响应后,API我想UIAlertController根据状态代码显示一个。

假设我得到的状态码是409,那么控制器会说“数据已经存在”

如何呈现alert controller以及在哪个类、服务类或任何其他类中view controller

视图控制器.h

- (IBAction)logIn:(id)sender {

    if (username.text == nil || [password.text isEqualToString:@""])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:
                                    @"all the fields are mendetary"
                                message:@"missing username or password " preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction
                                 actionWithTitle:@"OKAY" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action)
                                 {
                                     //[self dismissViewControllerAnimated:YES completion:nil];
                                 }];
        [alert addAction:action];
       [self presentViewController:alert animated:YES completion:nil];

    }
   else
   {
        [[service SharedInstance] logIn:[NSDictionary dictionaryWithObjectsAndKeys:username.text,@"username",password.text,@"password",nil] params:@"logIn" block:^(const BOOL success, id resultObject, NSError *error )
        {


            // [self performSegueWithIdentifier:@"Loggedin" sender:self];
         }];

    }

   username.text =@"";
    password.text =@"";


    }

服务.m

-(void)logIn:(NSDictionary *)Details params:(NSString *)params block:(ResponseBlock)block{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSError *error;
    NSString *URL = @"http://localhost:8080";
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:nil delegateQueue:nil];
    NSString *requestURL = [URL stringByAppendingString:@"/api/signupUser"];
    NSURL *url = [NSURL URLWithString:requestURL]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0]; NSData *data = [params dataUsingEncoding:NSDataBase64Encoding64CharacterLineLength];
    NSString *base64Encoded = [data base64EncodedStringWithOptions:0];
    NSLog(@"base64Encoded%@",base64Encoded);
    NSString *basicString = @"Basic";
    basicString = [NSString stringWithFormat:@"%@%@",basicString,base64Encoded];
    NSLog(@"basicString%@",basicString);
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:basicString forHTTPHeaderField:@"Authorization"];
    [request setHTTPMethod:@"POST"];
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:Details options:0 error:&error];

    [request setHTTPBody:bodyData];NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse *response, NSError *error)
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    long statusCode =[httpResponse statusCode];
    NSLog(@"response status code: %ld", statusCode);
f (error)
       {
           block(NO, response,error);
        }
    else
        {
           NSError *err = nil;
           id responseData = [NSJSONSerialization
           JSONObjectWithData:data options:kNilOptions error:&err];
           NSDictionary* headers= [(NSHTTPURLResponse *)response allHeaderFields];
           NSLog(@"all header fields %@",headers);
           [defaults removeObjectForKey:@"userToken"];
           NSLog(@"token %@",[defaults valueForKey:@"userToken"]);
           NSDate *expireDate = [[NSDate date]dateByAddingTimeInterval:60*25];
           [defaults setObject:expireDate forKey:@"sessionDate"];

            if(err)
            {
              block(NO, response, error);
            }
            else
            {
              block(YES, responseData,nil);
            }
              [task cancel];
        }
      }];
            [task resume];
        }
   @end

标签: objective-cuialertcontroller

解决方案


看起来您正在从服务文件进行一些 http 调用。这里有几个选项:

  1. 在 ViewController 中实现服务类的委托以在那里执行任何任务。
  2. 使用块。
  3. 在这里使用像 Rx 这样的框架。
  4. 或者如果您只需要显示警报,请将警报添加到当前窗口,例如

为此,我创建了一个扩展:

extension UIAlertController {
/// display alert with custom number of buttons
static func presentAlert(_ title: String?, message: String?, alertButtonTitles: [String], alertButtonStyles: [UIAlertActionStyle], vc: UIViewController, completion: @escaping (Int)->Void) -> Void
{
    let alert = UIAlertController(title: title,
                                  message: message,
                                  preferredStyle: UIAlertControllerStyle.alert)

    for title in alertButtonTitles {
        let actionObj = UIAlertAction(title: title,
                                      style: alertButtonStyles[alertButtonTitles.index(of: title)!], handler: { action in
                                        completion(alertButtonTitles.index(of: action.title!)!)
        })
        alert.addAction(actionObj)
    }
    vc.present(alert, animated: true, completion: nil)
}

} 利用:

UIAlertController.presentAlert("My Title", message: "My message", alertButtonTitles: "OK", alertButtonStyles: [.default], vc: (UIApplication.shared.keyWindow?.rootViewController)!, completion: { (btnIndex) in

    })

上面的代码是在窗口上添加 UiAlerController。


推荐阅读