这几天公司要求接VK的登陆和分享,结果上网一查关于IOS的接入一篇都没有?! 官方文档和最新sdk很多不一样写的也很不详细基本没啥用,爬了一天坑终于搞定了记录下来.
官方文档地址:https://vk.com/dev/ios_sdk
官方sdk地址:https://github.com/VKCOM/vk-ios-sdk
1.先去注册vk创建应用
2.运行sdk打出libVKSdk.a和VKSdkResources.bundle并和.h一起拷到Plugins/iOS 下
3.编写OC调用类放Plugins/iOS 下
VK.h
#import <Foundation/Foundation.h>
#import <GameKit/GameKit.h>
#import "VKSdk.h"
@interface VK : NSObject<VKSdkDelegate,VKSdkUIDelegate>
{
VKSdk * vkSdk;
}
+(VK*) GetInterface;
-(BOOL) handleOpenURL:(NSURL *)url options:(NSDictionary<NSString*, id>*)options;
@end
VK.mm
#import "VK.h"
#import "VKSdk.h"
@implementation VK
VK* VKInterface = NULL;
+(VK*) GetInterface{
if(VKInterface == NULL){
VKInterface = [[VK alloc] init];
}
return VKInterface;
}
-(BOOL) handleOpenURL:(NSURL *)url options:(NSDictionary<NSString*, id>*)options
{
[VKSdk processOpenURL:url fromApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
return YES;
}
- (void)Init:(NSString *)appId
{
vkSdk = [VKSdk initializeWithAppId:appId];
NSURL *URL = [NSURL URLWithString:@"https://api.vk.com"];
[NSURLRequest.class performSelector:NSSelectorFromString(@"setAllowsAnyHTTPSCertificate:forHost:")
withObject:NSNull.null // Just need to pass non-nil here to appear as a BOOL YES, using the NSNull.null singleton is pretty safe
withObject:[URL host]];
[vkSdk registerDelegate:self];
[vkSdk setUiDelegate:self];
}
- (void)Login
{
[VKSdk wakeUpSession:@[VK_PER_FRIENDS, VK_PER_WALL,VK_PER_PHOTOS] completeBlock:^(VKAuthorizationState state, NSError *error) {
switch (state) {
case VKAuthorizationAuthorized:
// User already autorized, and session is correct
if ([VKSdk accessToken]) {
NSLog(@"vkSdkAccessAuthorizationFinishedWithResultsssss : %@",[VKSdk accessToken].accessToken);
UnitySendMessage("Ios","IOSVKLoginCallBack",[[VKSdk accessToken].accessToken UTF8String]);
}else{
[VKSdk authorize:@[VK_PER_FRIENDS, VK_PER_WALL,VK_PER_PHOTOS]];
}
break;
case VKAuthorizationInitialized:
// User not yet authorized, proceed to next step
[VKSdk authorize:@[VK_PER_FRIENDS, VK_PER_WALL,VK_PER_PHOTOS]];
break;
default:
// Probably, network error occured, try call +[VKSdk wakeUpSession:completeBlock:] later
[VKSdk authorize:@[VK_PER_FRIENDS, VK_PER_WALL,VK_PER_PHOTOS]];
break;
}
}];
// [VKSdk authorize:@[VK_PER_FRIENDS, VK_PER_WALL,VK_PER_PHOTOS]];
}
-(void) Share:(NSString *)title description:(NSString*)description image:(UIImage *)image url:(NSString*)url
{
VKShareDialogController *shareDialog = [VKShareDialogController new]; //1
shareDialog.text = description; //2
uploadImages = [NSMutableArray new];
[uploadImages addObject:[VKUploadImage uploadImageWithImage:image andParams:[VKImageParameters jpegImageWithQuality:0.95]]];
shareDialog.uploadImages = uploadImages; //3
shareDialog.shareLink = [[VKShareLink alloc] initWithTitle:title link:[NSURL URLWithString:url]]; //4
[shareDialog setCompletionHandler:^(VKShareDialogController *dialog, VKShareDialogControllerResult result) {
[[self getCurrentVC] dismissViewControllerAnimated:YES completion:nil];
}]; //5
[[self getCurrentVC] presentViewController:shareDialog animated:YES completion:nil]; //6
//系统组件式分享不推荐
// NSArray *items = @[image, title , [NSURL URLWithString:url]]; //1
// UIActivityViewController *activityViewController = [[UIActivityViewController alloc]
// initWithActivityItems:items
// applicationActivities:@[[VKActivity new]]]; //2
// [activityViewController setValue:@"VK SDK" forKey:@"subject"]; //3
[activityViewController setCompletionHandler:nil]; //4
if (VK_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
UIPopoverPresentationController *popover = activityViewController.popoverPresentationController;
popover.sourceView = self.view;
popover.sourceRect = [tableView rectForRowAtIndexPath:indexPath];
} //5
// [[self getCurrentVC] presentViewController:activityViewController animated:YES completion:nil]; //6
}
- (void)vkSdkAccessAuthorizationFinishedWithResult:(VKAuthorizationResult *)result
{
if (result.token) {
// User successfully authorized, you may start working with VK API
NSLog(@"vkSdkAccessAuthorizationFinishedWithResultsssss : %@",result.token.accessToken);
UnitySendMessage("Ios","IOSVKLoginCallBack",[[VKSdk accessToken].accessToken UTF8String]);
}else{
NSLog(@"vkSdkAccessFail");
UnitySendMessage("Ios","IOSVKLoginCallBack","1");
}
// else if (result.error) {
// // User canceled authorization, or occured unresolving networking error. Reset your UI to initial state and try authorize user later
// NSLog(@"vkSdkAccessAuthorizationFinishedWithResulteeeee : %l",result.error.code);
// }
}
- (void)vkSdkAuthorizationStateUpdatedWithResult:(VKAuthorizationResult *)result
{
if (result.token) {
// User successfully authorized, you may start working with VK API
NSLog(@"vkSdkAccessAuthorizationFinishedWithResultsssss : %@",result.token.accessToken);
UnitySendMessage("Ios","IOSVKLoginCallBack",[[VKSdk accessToken].accessToken UTF8String]);
}else{
NSLog(@"vkSdkAccessFail");
UnitySendMessage("Ios","IOSVKLoginCallBack","1");
}
}
- (void)vkSdkUserAuthorizationFailed{
NSLog(@"vkSdkUserAuthorizationFailed");
}
- (void)vkSdkShouldPresentViewController:(UIViewController *)controller
{
NSLog(@"vkSdkShouldPresentViewController");
//[[self getCurrentVC].view addSubview:controller.view];
}
- (void)vkSdkNeedCaptchaEnter:(VKError *)captchaError
{
NSLog(@"vkSdkNeedCaptchaEnter");
VKCaptchaViewController *vc = [VKCaptchaViewController captchaControllerWithError:captchaError];
[vc presentIn:[self getCurrentVC]];
}
- (UIViewController *)getCurrentVC
{
//chyoadd
UIViewController *result = nil;
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
if (window.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows)
{
if (tmpWin.windowLevel == UIWindowLevelNormal)
{
window = tmpWin;
break;
}
}
}
UIView *frontView = [[window subviews] objectAtIndex:0];
id nextResponder = [frontView nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
result = nextResponder;
else
result = window.rootViewController;
return result;
}
@end
extern "C"
{
void VKInit(const char* appId)
{
[[VK GetInterface] Init:[NSString stringWithUTF8String:appId]];
}
void VKLogin(){
[[VK GetInterface] Login];
}
//这就是在 Unity 中调用的函数
void VKShare(const char* title,const char* description, const char* img , const char*url)
{
NSString* temp = [NSString stringWithUTF8String:img];
NSData* imageData = [[NSData alloc] initWithBase64EncodedString:temp options:NSDataBase64DecodingIgnoreUnknownCharacters];
[[VK GetInterface] Share:[NSString stringWithUTF8String:title] description:[NSString stringWithUTF8String:description] image:[UIImage imageWithData:imageData] url:[NSString stringWithUTF8String:url]];
}
}
要注意:
1.用vk登陆才可以调用vk分享,登陆的时候申请你需要的权限因为分享需要上传图片和发布动态VK_PER_WALL,VK_PER_PHOTOS 是必须的要不图片不显示分享不成功!!!
2.官方写的分享图片用shareDialog.vkImages 赋值图片id,也没说id怎么来的,好像图片也必须是用户相册里已有的,才会有id,所以基本没用. 看了半天源码发现可以自己传上去并使用 如下
NSMutableArray *uploadImages = [NSMutableArray new];
[uploadImages addObject:[VKUploadImage uploadImageWithImage:image andParams:[VKImageParameters pngImage]]];
shareDialog.uploadImages = uploadImages; //3
4.编写c#类,创建个名为Ios的物体并挂上去
using System.Collections;
using System.Runtime.InteropServices;
using UnityEngine;
public class Test : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void VKInit(string appId);
[DllImport("__Internal")]
private static extern void VKLogin();
[DllImport("__Internal")]
private static extern void VKShare(string title, string description, string img, string url);
private System.Action<bool> loginCallBack = null;
public void Start()
{
VKInit("你自己的appid");
}
public void IosVKLogin()
{
VKLogin();
}
public void IosVKShare()
{
StartCoroutine(EVKShare());
}
IEnumerator EVKShare()
{
WWW www = new WWW("http://jlfzzcdn.oss-cn-shanghai.aliyuncs.com/test/icon_48.png");
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log("error :: " + www.error);
}
VKShare("test", "info", System.Convert.ToBase64String(www.texture.EncodeToPNG()), "http://www.baidu.com");
}
public void IOSVKLoginCallBack(string code)
{
if (code.Equals("1"))
{
Debug.Log("登陆失败");
}
else
{
Debug.Log("登陆成功 : "+code);
}
}
}
5.导出项目xcode配置
UnityAppController.mm中openURL添加[[VK GetInterface] handleOpenURL:url options:options];
info添加
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>vk.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
和
<key>LSApplicationQueriesSchemes</key>
<array>
<string>vk</string>
<string>vk-share</string>
<string>vkauthorize</string>
</array>
设置urltypes
参考工程下载地址:https://download.csdn.net/download/zero870/12629742