前言

腾讯地图iOS SDK目前只提供了Objective-C版本的SDK, 因此如果是Swift项目, 则需要自己通过Bridging文件来将其引入

使用场景

Swift项目接入腾讯地图

接入流程

1、创建Swift项目, 本人采用的是StoryBoard创建的项目, 不过使用方法是一样的:

Swift接入腾讯地图SDK教程-LMLPHP

2、将SDK的framework和bundle导入项目中:

Swift接入腾讯地图SDK教程-LMLPHP

3、创建HeaderFile, 通常明明为"项目名称-Bridging-header", 即:TencentMapSwiftDemo-Bridging-header.h, 放在根目录(位置放在那里都可以, 区别只是路径不同):

Swift接入腾讯地图SDK教程-LMLPHP

4、进入项目配置, 选择TARGETS-TencentMapSwiftDemo, 然后进入到Build Setting中. 在搜索栏中搜索Bridging, 并在Objective-C Bridging Header选项中输入: $(SRCROOT)/TencentMapSwiftDemo-Bridging-header.h($(SRCROOT)为快捷指令, 可以直接识别项目的根路径):

Swift接入腾讯地图SDK教程-LMLPHP

如果编译没有出错, 则进行第五步, 否则请检查路径是否正确, 是否有多余的空格/换行等等, 比如下列报错, 就是本人在输入的时候不小心在最后加了一个空格导致的路径错误:

Swift接入腾讯地图SDK教程-LMLPHP

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两个依赖库:

Swift接入腾讯地图SDK教程-LMLPHP

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的检索

Swift接入腾讯地图SDK教程-LMLPHP

04-01 07:45