搜索几乎是每个app必备的功能,数据的实时搜索可以更好的满足客户的需求,提高客户体验。
实时搜索需要满足当输入第一个字的时候就要发起网络请求,当输入第二个字的时候要是第一请求没有完成就应该主动撤销,重新发起新的请求。本文重点解析iOS如何结合AFNetworking第三方库实现该功能。
主要代码如下:
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()
@property (nonatomic, strong) NSURLSessionDataTask *task;
@property (nonatomic, strong) UITextField *field;
@property (nonatomic, assign) NSInteger inputCount;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.field = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
self.field.center = self.view.center;
self.field.placeholder = @"搜索";
self.field.font = [UIFont systemFontOfSize:14];
self.field.returnKeyType = UIReturnKeySearch;
self.field.borderStyle = UITextBorderStyleRoundedRect;
[self.field addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[self.view addSubview:self.field];
}
- (void)textFieldDidChange:(UITextField *)textField {
self.inputCount ++;
//当检测到textfield发生变化0.7秒后会调用该方法
[self performSelector:@selector(requestKeyWorld:) withObject:@(self.inputCount) afterDelay:0.7f];
}
- (void)requestKeyWorld:(NSNumber *)count {
//当用户停止输入0.7秒后self.inputCount会等于count这个时候去发送请求
if (self.inputCount == [count integerValue]) {
if ([self.field.text isEqualToString:@""]) {
//这里加入你的默认的数据.....
return;
}
NSString *urlStr = @"https://....";
NSDictionary *dict = @{@"data":@"请求参数"};
[self.task cancel]; //这步是撤销之前的请求
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer.timeoutInterval = 13.f;
self.task = [manager POST:urlStr parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (responseObject) {
NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//加入你的代码......
}
} failure:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
温馨提示
这里为什么不用textField的代理这个方法来实现监测textField的内容发生变化呢?
-- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
这里需要注意的是这个代理方法不能监测到直接点击键盘上面的文字如图: