iOS開發(fā)之封裝高德地圖搜索管理類

一、前言

我們?cè)陧?xiàng)目開發(fā)中經(jīng)常會(huì)用到第三方的SDK等來實(shí)現(xiàn)項(xiàng)目所需要的功能,很多時(shí)候拿到別人的東西并不是所有的都適合我們自己的項(xiàng)目,為了方便使用或者擴(kuò)展更多功能,或者為了對(duì)第三方的代碼進(jìn)行更合理的管理,經(jīng)常要對(duì)他們的代碼和功能進(jìn)行封裝。以此來達(dá)到方便管理,更便于閱讀,功能更適合自己項(xiàng)目等功能,而且有些東西進(jìn)行一次封裝,多處可以使用,這樣就很方便。

我們以高德地圖搜索類AMapSearchAPI為例子,進(jìn)行該功能的封裝和在項(xiàng)目中的使用。

二、高德地圖搜索管理類AMapSearchAPI

AMapSearchAPI里提供了各種搜索功能的Api,比如關(guān)鍵字查詢Api:

/**
 * @brief POI 關(guān)鍵字查詢接口
 * @param request 查詢選項(xiàng)。具體屬性字段請(qǐng)參考 AMapPOIKeywordsSearchRequest 類。
 */
- (void)AMapPOIKeywordsSearch:(AMapPOIKeywordsSearchRequest *)request;

還有各種周邊查詢、逆地理編碼查詢等等,這些Api都有各自的代理回調(diào),比如關(guān)鍵字檢索回調(diào)代理:

/**
 * @brief POI查詢回調(diào)函數(shù)
 * @param request  發(fā)起的請(qǐng)求,具體字段參考 AMapPOISearchBaseRequest 及其子類。
 * @param response 響應(yīng)結(jié)果,具體字段參考 AMapPOISearchResponse 。
 */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response;

提供了各種搜索功能和回調(diào)代理。

三、功能實(shí)現(xiàn)

這里考慮到項(xiàng)目中經(jīng)常使用,所以創(chuàng)建一個(gè)單例作為項(xiàng)目中高德地圖搜索管理類。

1、實(shí)現(xiàn)代碼

DDSearchManager.h

#import <Foundation/Foundation.h>

typedef void(^keyWordSearchBlock)(NSMutableArray *pointAnnotaions);//用于關(guān)鍵字檢索回調(diào)數(shù)據(jù)
typedef void(^tipsSearchBlock)(NSArray *tips);//用于tip搜索回調(diào)數(shù)據(jù)

@interface DDSearchManager : NSObject

+ (instancetype)sharedManager;

/* 2比1查詢速度快;1的數(shù)據(jù)量比2大 。*/

/*
 1、關(guān)鍵字檢索
 
 keyword為檢索關(guān)鍵字;city可為空;block返回檢索完后的數(shù)組,數(shù)組中是MAPointAnnotation的對(duì)象
 
 注意:關(guān)鍵字未設(shè)置城市信息(默認(rèn)為全國搜索)時(shí),如果涉及多個(gè)城市數(shù)據(jù)返回,僅會(huì)返回建議城市,請(qǐng)根據(jù)APP需求,選取城市進(jìn)行搜索。
 */
- (void)keyWordsSearch:(NSString *)keyword city:(NSString *)city returnBlock:(keyWordSearchBlock)block;


/*
 2、輸入提示查詢
 
 block回調(diào)查詢后的數(shù)組,該數(shù)組里是AMapTip對(duì)象
 */
- (void)inputTipsSearch:(NSString *)tips city:(NSString *)city returnBlock:(tipsSearchBlock)block;

@end

DDSearchManager.m

#import "DDSearchManager.h"

#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>

@interface DDSearchManager ()<AMapSearchDelegate>

//高德地圖搜索管理類
@property (nonatomic, strong) AMapSearchAPI *searchAPI;

@property (nonatomic, copy) keyWordSearchBlock keyWordSearchBlock;
@property (nonatomic, copy) tipsSearchBlock tipSearchBlock;

@end

@implementation DDSearchManager

+ (instancetype)sharedManager {
    static DDSearchManager *manager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[self alloc]init];
    });
    return manager;
}

/// 關(guān)鍵字查詢
- (void)keyWordsSearch:(NSString *)keyword city:(NSString *)city returnBlock:(keyWordSearchBlock)block
{
    if (keyword.length) {
        
        self.keyWordSearchBlock = block;
        
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc]init];
        
        request.keywords = keyword;
        if (city.length) {
            request.city = city;
            /* 搜索SDK 3.2.0 中新增加的功能,只搜索本城市的POI。*/
            request.cityLimit = YES;
        }
        /*返回?cái)U(kuò)展信息*/
        request.requireExtension = YES;
        request.requireSubPOIs = YES;
        
        /*發(fā)起關(guān)鍵字搜索*/
        [self.searchAPI AMapPOIKeywordsSearch:request];
    }
}

/// 輸入提示查詢
- (void)inputTipsSearch:(NSString *)tips city:(NSString *)city returnBlock:(tipsSearchBlock)block {
    if (tips.length) {
        
        self.tipSearchBlock = block;
        
        AMapInputTipsSearchRequest *request = [[AMapInputTipsSearchRequest alloc]init];
        
        request.keywords = tips;
        if (city.length) {
            request.city = city;
            request.cityLimit = YES;
        }
        
        /*發(fā)起關(guān)鍵字搜索*/
        [self.searchAPI AMapInputTipsSearch:request];
    }
}

#pragma mark delegate
#pragma AMapSearchDelegate
//關(guān)鍵字查詢代理回調(diào)
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0) {
        return;
    }
    
    NSMutableArray *poiAnnitations = [[NSMutableArray alloc]init];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        [annotation setCoordinate:CLLocationCoordinate2DMake(obj.location.latitude, obj.location.longitude)];
        [annotation setTitle:obj.name];
        [annotation setSubtitle:obj.address];
        
        [poiAnnitations addObject:annotation];
    }];
    //回調(diào)檢索結(jié)果,回調(diào)數(shù)組是MAPointAnnotation的對(duì)象集合
    if (self.keyWordSearchBlock) {
        self.keyWordSearchBlock (poiAnnitations);
    }
}
//輸入提示查詢代理回調(diào)
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    if (self.tipSearchBlock)
    {
        NSMutableArray *arr = [NSMutableArray array];
        for (int i=0; i<response.tips.count; i++)
        {
            //輸入提示類
            AMapTip *tip = [response.tips objectAtIndex:i];
            
            if (tip.location.latitude!=0 && ![tip.uid isEqualToString:@""])
            {
                [arr addObject:tip];
            }
        }
        //回調(diào)tip檢索結(jié)果,回調(diào)數(shù)組中是AMapTip對(duì)象的集合。
        self.tipSearchBlock (arr);
    }
}

#pragma mark set/get
- (AMapSearchAPI *)searchAPI {
    if (!_searchAPI) {
        _searchAPI = [[AMapSearchAPI alloc]init];
        _searchAPI.delegate = self;
    }
    return _searchAPI;
}

@end

2、調(diào)用

這里隨便截取了一段示例代碼,發(fā)起tip檢索,然后回調(diào)數(shù)據(jù),更新數(shù)據(jù)源,然后刷新tableView的列表功能。

[[DDSearchManager searchManager] inputTipsSearch:text city:self.selectCityBtn.titleLabel.text returnBlock:^(NSArray *tips) {

    [_searchArr removeAllObjects];
    [_searchArr addObjectsFromArray:tips]];
    [_tableView reloadData];
}];

這里有一個(gè)問題就是刷新tableView的時(shí)候如果給cell賦值,你得知道回調(diào)數(shù)組里面是什么類型的數(shù)據(jù),不然不知道怎么賦值。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = kCellReuseIdentifier;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellReuseIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellReuseIdentifier];
    }
    
    AMapPOI *poi = self.dataSource[indexPath.row];
    NSLog(@"poi.name :%@     poi.address:%@ ",poi.name,poi.address);
    cell.textLabel.text = poi.name;
    cell.detailTextLabel.text = poi.address;

    return cell;
}

四、問題思考

以上一個(gè)高德地圖的搜索管理類就簡單的完成了,但是就這樣能算是封裝嗎?我覺得不能算完全封裝,原因有如下:

1、結(jié)構(gòu)都通過數(shù)據(jù)回調(diào),使用的人怎么會(huì)知道數(shù)組里是什么呢?
2、封裝的話一般不應(yīng)該將原來的東西暴露在外,這里雖然DDSearchManager.h沒有暴露有關(guān)于高德地圖SDK,AMapSearchAPI等,但是在使用的時(shí)候,還得用高德SDK中的類AMapTip和MAPointAnnotation,這樣的封裝不夠徹底。

所以以上封裝還算不到封裝,如果算也只是個(gè)半成品,不夠徹底。所以我們需要繼續(xù)優(yōu)化,繼續(xù)封裝。

五、繼續(xù)封裝

1、創(chuàng)建一個(gè)定義搜索結(jié)果的基礎(chǔ)數(shù)據(jù)類型的類DDSearchObj

DDSearchObj.h
//
//  DDSearchObj.h
//  GDAddressSelected
//  該文件定義了搜索結(jié)果的基礎(chǔ)數(shù)據(jù)類型。
//

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface DDSearchObj : NSObject

@end

///輸入提示
@interface DDSearchTip : DDSearchObj

///名稱
@property (nonatomic, copy) NSString   *name;
///區(qū)域編碼
@property (nonatomic, copy) NSString   *adcode;
///所屬區(qū)域
@property (nonatomic, copy) NSString   *district;
///地址
@property (nonatomic, copy) NSString   *address;
///經(jīng)緯度
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

@end

///點(diǎn)標(biāo)注數(shù)據(jù)
@interface DDSearchPointAnnotation : DDSearchObj

///經(jīng)緯度
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
///標(biāo)題
@property (nonatomic, copy) NSString *title;
///副標(biāo)題
@property (nonatomic, copy) NSString *subtitle;

@end

這個(gè)類里面有DDSearchTip和DDSearchPointAnnotation,這分別是tip搜索回調(diào)數(shù)據(jù)類型的類和關(guān)鍵字搜索回調(diào)數(shù)據(jù)的類,這兩個(gè)類有各自的屬性,視項(xiàng)目情況自己添加更多屬性等。

DDSearchObj.m
#import "DDSearchObj.h"

@implementation DDSearchObj

@end


@implementation DDSearchPointAnnotation

@end


@implementation DDSearchTip

@end

2、優(yōu)化DDSearchManager類

DDSearchManager.h
#import <Foundation/Foundation.h>
#import "DDSearchObj.h"

//關(guān)鍵字搜索數(shù)據(jù)回調(diào)block
typedef void(^keyWordSearchBlock)(NSArray <__kindof DDSearchPointAnnotation*> *pointAnnotaions);
//tip搜索數(shù)據(jù)回調(diào)block
typedef void(^tipsSearchBlock)(NSArray <__kindof DDSearchTip*> *tips);

@interface DDSearchManager : NSObject

+ (instancetype)sharedManager;

/* 2比1查詢速度快;1的數(shù)據(jù)量比2大 。*/

/*
 1、關(guān)鍵字檢索
 
 keyword為檢索關(guān)鍵字;city可為空;block返回檢索完后的數(shù)組,數(shù)組中是MAPointAnnotation的對(duì)象
 
 注意:關(guān)鍵字未設(shè)置城市信息(默認(rèn)為全國搜索)時(shí),如果涉及多個(gè)城市數(shù)據(jù)返回,僅會(huì)返回建議城市,請(qǐng)根據(jù)APP需求,選取城市進(jìn)行搜索。
 */
- (void)keyWordsSearch:(NSString *)keyword city:(NSString *)city returnBlock:(keyWordSearchBlock)block;

/*
 2、輸入提示查詢
 
 block回調(diào)查詢后的數(shù)組,該數(shù)組里是AMapTip對(duì)象
 */
- (void)inputTipsSearch:(NSString *)tips city:(NSString *)city returnBlock:(tipsSearchBlock)block;

@end

引入DDSearchObj.h頭文件,將數(shù)據(jù)回調(diào)的block用<__kindof DDSearchPointAnnotation*>修飾,表示該數(shù)組里面只能是DDSearchPointAnnotation類型的數(shù)據(jù),這樣的話,當(dāng)使用該類的人用此方法的時(shí)候block回調(diào)里面就會(huì)知道,這個(gè)回調(diào)數(shù)據(jù)是DDSearchPointAnnotation的數(shù)組,而不是其他什么東西的數(shù)據(jù)。

DDSearchManager.m
#import "DDSearchManager.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>

@interface DDSearchManager ()<AMapSearchDelegate>

@property (nonatomic, strong) AMapSearchAPI *searchAPI;

@property (nonatomic, copy) keyWordSearchBlock keyWordSearchBlock;
@property (nonatomic, copy) tipsSearchBlock tipSearchBlock;

@end

@implementation DDSearchManager

+ (instancetype)sharedManager {
    static DDSearchManager *manager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[self alloc]init];
    });
    return manager;
}

/// 關(guān)鍵字查詢
- (void)keyWordsSearch:(NSString *)keyword city:(NSString *)city returnBlock:(keyWordSearchBlock)block
{
    if (keyword.length) {
        
        self.keyWordSearchBlock = block;
        
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc]init];
        
        request.keywords = keyword;
        if (city.length) {
            request.city = city;
            /* 搜索SDK 3.2.0 中新增加的功能,只搜索本城市的POI。*/
            request.cityLimit = YES;
        }
        /*返回?cái)U(kuò)展信息*/
        request.requireExtension = YES;
        request.requireSubPOIs = YES;
        
        /*發(fā)起關(guān)鍵字搜索*/
        [self.searchAPI AMapPOIKeywordsSearch:request];
    }
}

/// 輸入提示查詢
- (void)inputTipsSearch:(NSString *)tips city:(NSString *)city returnBlock:(tipsSearchBlock)block {
    if (tips.length) {
        
        self.tipSearchBlock = block;
        
        AMapInputTipsSearchRequest *request = [[AMapInputTipsSearchRequest alloc]init];
        
        request.keywords = tips;
        if (city.length) {
            request.city = city;
            request.cityLimit = YES;
        }
        
        /*發(fā)起關(guān)鍵字搜索*/
        [self.searchAPI AMapInputTipsSearch:request];
    }
}

#pragma mark delegate
#pragma AMapSearchDelegate
//關(guān)鍵字查詢代理回調(diào)
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0) {
        return;
    }
    
    NSMutableArray *poiAnnitations = [[NSMutableArray alloc]init];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
//        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
//        [annotation setCoordinate:CLLocationCoordinate2DMake(obj.location.latitude, obj.location.longitude)];
//        [annotation setTitle:obj.name];
//        [annotation setSubtitle:obj.address];
        
        DDSearchPointAnnotation *annotation = [[DDSearchPointAnnotation alloc] init];
        [annotation setCoordinate:CLLocationCoordinate2DMake(obj.location.latitude, obj.location.longitude)];
        [annotation setTitle:obj.name];
        [annotation setSubtitle:obj.address];
        
        [poiAnnitations addObject:annotation];
    }];

    if (self.keyWordSearchBlock) {
        self.keyWordSearchBlock (poiAnnitations);
    }
}
//輸入提示查詢代理回調(diào)
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    if (self.tipSearchBlock)
    {
        NSMutableArray *arr = [NSMutableArray array];
        for (int i=0; i<response.tips.count; i++)
        {
            AMapTip *tip = [response.tips objectAtIndex:i];
            
//            if (tip.location.latitude!=0 && ![tip.uid isEqualToString:@""])
//            {
//                [arr addObject:tip];
//            }
            
            if (tip.location.latitude!=0 && ![tip.uid isEqualToString:@""])
            {
                DDSearchTip *ddTip = [[DDSearchTip alloc] init];
                ddTip.name = tip.name;
                ddTip.adcode = tip.adcode;
                ddTip.district = tip.name;
                ddTip.address = tip.address;
                ddTip.coordinate = CLLocationCoordinate2DMake(tip.location.latitude, tip.location.longitude);
                
                [arr addObject:tip];
            }
            
        }
        self.tipSearchBlock (arr);
    }
}

#pragma mark set/get
- (AMapSearchAPI *)searchAPI {
    if (!_searchAPI) {
        _searchAPI = [[AMapSearchAPI alloc]init];
        _searchAPI.delegate = self;
    }
    return _searchAPI;
}

@end

這里我將原來的寫法注釋掉,稍作了變動(dòng)。將高德地圖的數(shù)據(jù)轉(zhuǎn)化成我們自己的數(shù)據(jù)存儲(chǔ),并回調(diào)。這樣的話,在外部使用的時(shí)候,用的人不用關(guān)心高德地圖類里面的實(shí)現(xiàn)過程,中需要知道當(dāng)發(fā)起檢索時(shí)回調(diào),回調(diào)的數(shù)據(jù)在相應(yīng)的地方去拿數(shù)據(jù)就好了。

3、發(fā)起檢索

[[DDSearchManager sharedManager] keyWordsSearch:@"北京大學(xué)" city:@"北京" returnBlock:^(NSArray<__kindof DDSearchPointAnnotation *> *pointAnnotaions) {
    
    for (DDSearchPointAnnotation *annotation in pointAnnotaions)
    {
        NSLog(@"%@,%@,%f,%f",annotation.title,annotation.subtitle,annotation.coordinate.latitude,annotation.coordinate.longitude);
    }
}];

這里當(dāng)我們調(diào)用該方法進(jìn)行關(guān)鍵字檢索的時(shí)候,在block回調(diào)中就能知道回調(diào)的數(shù)據(jù)是DDSearchPointAnnotation對(duì)象的數(shù)組,不用關(guān)心高德地圖內(nèi)部檢索的結(jié)果是什么,只需要進(jìn)入DDSearchPointAnnotation類里,就可以知道回調(diào)的數(shù)據(jù)你需要取哪些值。

這樣避免了高德SDK類的外部暴露出來,這就簡單的封裝了一個(gè)高德地圖檢索的管理類,這里是用block進(jìn)行數(shù)據(jù)回調(diào)的,當(dāng)然小伙伴們也可以用代理的方式。

六、總結(jié)

  • 當(dāng)我們封裝一個(gè)第三方的功能的時(shí)候,封裝使得它能夠更好的服務(wù)于我們自己的項(xiàng)目。

  • 如果要封裝盡量封裝的徹底一點(diǎn),盡量不要暴露第三方的東西,你的封裝類依賴于三方,實(shí)現(xiàn)的時(shí)候還依賴于三方類,這樣的封裝總感覺不是很完美。

  • 當(dāng)然有的小伙伴說了不進(jìn)行上面的優(yōu)化封裝部分也行,也能用,就看個(gè)人怎么理解了。

代碼:https://github.com/Mexiang/DDSearchManager

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容