Swift接入騰訊位置服務地圖SDK

前言

騰訊地圖iOS SDK目前只提供了Objective-C版本的SDK, 因此如果是Swift項目, 則需要自己通過Bridging文件來將其引入

使用場景

Swift項目接入騰訊地圖

接入流程

1、創建Swift項目, 本人採用的是StoryBoard創建的項目, 不過使用方法是一樣的:

2、將SDK的framework和bundle導入項目中:

3、創建HeaderFile, 通常明明爲"項目名稱-Bridging-header", 即:TencentMapSwiftDemo-Bridging-header.h, 放在根目錄(位置放在那裏都可以, 區別只是路徑不同):

4、進入項目配置, 選擇TARGETS-TencentMapSwiftDemo, 然後進入到Build Setting中. 在搜索欄中搜索Bridging, 並在Objective-C Bridging Header選項中輸入: $(SRCROOT)/TencentMapSwiftDemo-Bridging-header.h($(SRCROOT)爲快捷指令, 可以直接識別項目的根路徑):

如果編譯沒有出錯, 則進行第五步, 否則請檢查路徑是否正確, 是否有多餘的空格/換行等等, 比如下列報錯, 就是本人在輸入的時候不小心在最後加了一個空格導致的路徑錯誤:

5、編譯通過的話就可以在BridgingHeader文件中導入Objective-C的框架了:

#ifndef TencentMapSwiftDemo_Bridging_header_h
#define TencentMapSwiftDemo_Bridging_header_h

#import <QMapKit/QMapKit.h>
#import <QMapKit/QMSSearchKit.h>

#endif /* TencentMapSwiftDemo_Bridging_header_h */

6、別忘了根據文檔所示, 需要添加libsqlite3.tbd、libc++.tbd兩個依賴庫:

7、到此就可以使用地圖SDK了, 首先在AppDelegate裏面配置好Key:

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        QMapServices.shared().apiKey = "我的Key"
        QMSSearchServices.shared()?.apiKey = "我的Key"
        
        return true
    }
}

8、最後, 附加一段ViewController中的基本使用:

import UIKit

class ViewController: UIViewController, QMSSearchDelegate {

    var mapView : QMapView!
    lazy var tencentSearcher : QMSSearcher = {
        return QMSSearcher.init(delegate: self)
    }()
    
    
    // MARK: 配置MapView
    func setupMapView() {
        mapView = QMapView.init(frame: UIScreen.main.bounds)
        view.addSubview(mapView)
    }
    
    // MARK: 配置Searcher
    func searchCurrentPositionPois() {
        let currentCoordinate = mapView.centerCoordinate
        let searchOption = QMSPoiSearchOption()
        searchOption.keyword = "美食"
        searchOption.setBoundaryByNearbyWithCenter(currentCoordinate, radius: 1000, autoExtend: false)
        tencentSearcher.search(with: searchOption)
    }
    
    // MARK: Searcher 代理方法
    func search(with poiSearchOption: QMSPoiSearchOption, didReceive poiSearchResult: QMSPoiSearchResult) {
        print(poiSearchResult)
    }
    
    func search(with searchOption: QMSSearchOption, didFailWithError error: Error) {
        print(error)
    }
    
    // MARK: 生命週期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 配置MapView
        setupMapView()
        
        // 發起POI檢索
        searchCurrentPositionPois()
    }
}

圖片示例:展示基本地圖和座標點附近POI的檢索

作者:麪糊

鏈接:https://www.jianshu.com/p/efa24e1487f4

來源:簡書

著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章