How to add the WeChat API to a Swift project?
Asked Answered
V

3

8

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 writing my project in Swift.

What I've tried

I added the following following SDK files to my project

libWeChatSDK.a
WechatAuthSDK.h
WXApi.h
WXApiObject.h

I tried following the advice on this answer for using a bridging header.

MyProject-Bridging-Header.h

#import "WXApi.h"

Errors

However, I'm still not able to use the WeChat API in my code. I'm getting the following errors:

WXApiObject.h

- (void) setThumbImage:(UIImage *)image;    // Expected a type

WXApi.h

+(BOOL) sendAuthReq:(SendAuthReq*) req viewController : (UIViewController*) viewController delegate:(id<WXApiDelegate>) delegate;
// Expected a type

And

<unknown>:0: error: failed to import bridging header '[my path]/MyProject-Bridging-Header.h' 

Question

Has anyone been successful in using the WeChat API with a Swift Project? I would love to see a brief list of steps or some sample code. I don't mind if any supplemental links are to Chinese resources.

Viera answered 1/3, 2016 at 9:22 Comment(1)
wechat really need to add this into their documentHaerle
V
27

See @chengsam's answer for newer updates to this process.

How to use the WeChat SDK in your Swift project

The official WeChat developer English instructions seem to be out of date and incomplete. The Chinese instructions are better but only deal with Objective-C. The steps below show how to add the WeChat (weixin 微信) SDK to your project.

Apply for a WeChat App ID

The English site is dev.wechat.com. I was never able to successfully register on the English site, though. I ended up using the Chinese site: open.weixin.qq.com. How to do that is beyond the scope of this answer, but if you don't know Chinese, Google translate can help. Note that you will probably also need a phone number in China.

After your app is approved (you only have to describe your app, no need to provide a binary or source code), you will get an App ID, which you will use in your code.

Download the WeChat SDK

You can try to use the SDK from the English site, but since things seem to be more current at the time of this writing on the Chinese site, that is where I downloaded the SDK for these instructions.

I downloaded the SDK from this page and the link for WeChat SDK version 1.6.2 is here. You will probably want to use the most recent version, though, whatever that may be in the future.

Copy the SDK files into your Xcode project

For organization sake, I put all the files in the same group in my project navigator. (The actual files are still in the project's root folder.)

enter image description here

Bug fix:

In SDK 1.6.2 the issue described in the question appears and is solved by @Anbu.Karthik's answer. Simply add #import <UIKit/UIKit.h> to WXApiObject.h. (You can actually replace #import <Foundation/Foundation.h> with it.) If you are using some SDK version after 1.6.2 this may no longer be an issue, so you may want to just complete the other steps before modifying the SDK files.

Add a Bridging Header

Note that several of the SDK files are Objective-C header (.h) files. In order to use them in your Swift project, you need to add a Bridging Header file to your project. Add a new file (File > New > File... > iOS > Source > Header File ) and call it YourProjectName-Bridging-Header.h.

Add the following line to this file.

#import "WXApi.h"

In my project this is the only line in my bridging header file because it's the only line you need for the WeChat SDK. (There were some other auto generated lines of code when I created the header file, but I just commented them out because I didn't know what they did. I will come back and edit this answer later if I find out they are useful.)

See here, here, and here for more help with adding a bridging header.

There is no need to import any of the WeChat SDK files in your Swift code files now.

Add the required frameworks and libraries

Go to the General tab of your project and scroll down to Linked Frameworks and Libraries. Click the plus (+) button to add the following required frameworks and libraries.

  • libc++.tbd
  • CoreTelephony.framework
  • libsqlite3.tbd
  • libz.tbd
  • SystemConfiguration.framework
  • libWeChatSDK.a (This one should be there already if you have copied it into your project.)

It should now look like this:

enter image description here

The CoreTelephony was mentioned in the readme and the libc++ was mentioned in the online SDK installation instructions but not vice versa. I just added them both to be safe. Feel free to leave a comment if either of these is not actually required.

Add URL Scheme

Go to the Info tab of your project and expand the URL Types item.

Add a type where the identifier is weixin and the URL Schemes is the AppID that you should have gotten after you successfully registered your app with WeChat.

enter image description here

Edit AppDelegate

Edit your AppDelegate.swift file to contain the following functions. Be sure to use your AppID rather than the example one. Other than that you can pretty much copy and paste.

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // WeChat: replace with your AppID
        WXApi.registerApp("wx68aa08d12b601234")
        
        return true
    }
    
    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)
    }
    
    func onReq(req: BaseReq!) {
        // do optional stuff
    }
    
    func onResp(resp: BaseResp!) {
        // do optional stuff
    }

    // ...
    
}

See the sample demo app for the optional stuff you can do in onReq and onResp. (The current link is here but if that link is broken, then look for the Sample Demo in the official WeChat developer docs.)

Edit Info.plist

Right click on Info.plist and choose Open As > Source Code. Then add the following two keys before the final </dict>:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>weixin</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

According to the readme included with the SDK, this is necessary because iOS 9 limits http access.

Use the WeChat API

At this point you should be able to start using the WeChat API within your Swift code. I may add a couple more API examples later, but the following is a proof of concept.

Send a text message

let message = SendMessageToWXReq()
message.text = "Hello WeChat"
message.bText = true
message.scene = Int32(WXSceneSession.rawValue) // WXSceneSession
WXApi.sendReq(message)

I was not able to use the Objective-C defined enum WXSceneSession, so I just used its integer value. There is probably a better solution, but this works for now.


This solution above was tested with Xcode 7.2 and iOS 9.2.

Viera answered 8/3, 2016 at 8:22 Comment(6)
is there a way to use "Login with WeChat"? I have been trying that with no success yet.Medarda
@Medarda I figured out how to add login: #38069529Veats
Now be aware that : return WXApi.handleOpenURL(url, delegate: self) become return WXApi.handleOpen(url, delegate: self)Rembert
@Ben, thank you for the comment. Besides this, did everything else work? I haven't done this for a while and I don't know what other changes there might be.Viera
This worked for me except neither of these functions get called on WXApi.send(req): func onReq(req: BaseReq!) { // do optional stuff } func onResp(resp: BaseResp!) { // do optional stuff }Demurrer
help on adding bridging header mycodetips.com/ios/…Haerle
A
3

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:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>weixin</string>
</array>

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

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

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
}
Augment answered 18/7, 2017 at 16:51 Comment(9)
when using pod, WXApi can't be imported as a module.Mulish
@zssr For me, there's no need to import WXApi.Augment
really weird! but i just tried again. still doesn't work.Mulish
@zssr I just tried to change from manual install to CocoaPods, but apparently they're not making a great pod yet. In my bridging header I have #import "../../Pods/WechatOpenSDK/OpenSDK1.8.0/WXApi.h" Which would change everytime the version is updatedBassinet
@Bassinet , yeah, it's not that elegant. I chose the manual way.Mulish
@zssr I have updated the answer, please check to see if it works for you.Augment
@Bassinet I have updated the answer, please check to see if it works for you.Augment
@Augment Is there a way to share Image to Wechat from our swift app. If yes then how many images can be shared at a time.Ngo
@MandeepSingh You may refer to developers.weixin.qq.com/doc/oplatform/Mobile_App/…, you can share image using WXImageObjectAugment
N
1

Expected a type --> for this error , check once the Apple Documentation for UIImage it's in UIKit, not Foundation. The docs are now all targeted at Swift.

@import UIKit;

In objective-c.

#import <UIKit/UIKit.h> 

which you need at the top of your file (no need for the Foundation import either).

failed to import bridging header --> you were made the small Mistake see this link, it helps you

Nonie answered 1/3, 2016 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.