objective-c - 在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
解决方案
看起来您正在从服务文件进行一些 http 调用。这里有几个选项:
- 在 ViewController 中实现服务类的委托以在那里执行任何任务。
- 使用块。
- 在这里使用像 Rx 这样的框架。
- 或者如果您只需要显示警报,请将警报添加到当前窗口,例如
为此,我创建了一个扩展:
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。
推荐阅读
- azure - 如何在 Azure 上部署一个 Sping Restfull api
- ruby-on-rails - 导轨。将单个用户的角色切换为买家/卖家,如 Fiverr
- android - Android 应用程序从 Delphi 10.3.1 迁移到 10.3.2
- node.js - 如何将超级代理(或任何请求库)安装到无服务器框架 AWS Lambda 函数中?
- javascript - Angular 8在页面加载错误后添加类:ExpressionChangedAfterItHasBeenCheckedError
- pointers - 在 ARM 汇编中,为什么我的值没有更新?
- c# - 无法在 Visual Studio 2017 上运行 Xunit 单元测试
- angular - 如何杀死Angular中的组件?
- c++ - QGridLayout 限制中的多个小部件
- linux - linux下终端编译代码的问题