How to add the WeChat API to a Swift project?

前端 未结 3 1083
囚心锁ツ
囚心锁ツ 2020-11-30 11:56

I\'m trying to add WeChat sharing functionality to my project. However the SDK files, documentation, development guides, and sample project are all in Objective-C. I am writ

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 12:18

    Suragch's answer described how to add WeChat API to your app in details. But after my implementation, I figured out the procedure can be simpler now. Below I will highlight some of the changes compared to that answer. You may refer to that answer for more details.

    Download the SDK

    Using CocoaPods

    pod 'WechatOpenSDK'
    

    Manual

    Download the SDK from the Resource Page. There are two versions at the time of writing, the first one includes payment function and the second one does not. Choose the one as per your need. After downloading, copy the files to your project. Add the required frameworks and libraries according to that answer. This step is not required if you install using CocoaPods.

    Add bridging header

    As WXApi is written in Objective-C, we have to create a bridging header to use it in Swift projects. See this link on how to add a bridging header.

    After creating the bridging header, insert the following line:

    #import "WXApi.h"
    

    iOS 9+ Changes

    In AppDelegate, the following two methods are used before iOS 9:

    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
        return WXApi.handleOpenURL(url, delegate: self)
    }
    
    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
        return WXApi.handleOpenURL(url, delegate: self)
    }
    

    In iOS 9, the above two methods are deprecated and the following one is used:

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }
    

    Edit Info.plist

    In my case, only the following is needed:

    LSApplicationQueriesSchemes
    
        weixin
    
    

    If it doesn't work for you, then add the following as well:

    NSAppTransportSecurity
    
        NSAllowsArbitraryLoads
        
    
    

    Extra

    To check if WeChat app is installed on the phone, use the following code:

    if WXApi.isWXAppInstalled() {
        // do something with WeChat...
    } else {
        // WeChat app is not installed, show error message
    }
    

提交回复
热议问题