2

Unity3D研究院之在IOS中调用新浪微博接口(三十六)

 3 years ago
source link: https://www.xuanyusong.com/archives/1794
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Unity3D研究院之在IOS中调用新浪微博接口(三十六)

最近有朋友问MOMO如何在Unity3D中使用新浪微博接口,刚好最近我们的工程中也需要添加新浪微博接口,那么MOMO就捎带手学习一下。目前我已经成功将新浪微博接口移植在Unity3D中,希望可以帮助到之前问我的那个朋友,哇咔咔。OK!如下图所示,这是我在U3D程序中发出的微薄消息,图片是在U3D中截屏的,效果还是不错的吧,蛤蛤。

在继续学习之前请朋友确认你所需要的微薄密钥是否准备完毕。

1.没有密钥的朋友

请在这里注册一个移动应用,http://open.weibo.com/ 。注册成功后在应用信息-》基本信息中即可获得APP KEY 和 APP SECRET,没有这两个KEY你是无法发送微薄的。 仅仅这些还是不够,因为是刚刚注册的新密钥所以是不能被公众所使用的,你应当继续在 应用信息-> 测试帐号 中添加测试账号,只有添加过的测试帐号才能使用新注册的密钥发送微薄。

2.有密钥的朋友

可以直接使用你的密钥来进行开发。

接着开始下载IOS新浪微博的开发包 http://code.google.com/p/sinaweibosdkforoauth2/downloads/list 将下载的SinaWeiBoSDK2 -> src -> SinaWeiBoSDK 开发包添加至Unity3D 生成的工程当中。

如下图所示,SinaWeiBoSDK文件夹就是刚刚下载的开发包,另外,记得将Security.framework加入在工程中。最下面的MyViewController 就是负责在U3D之上发送微薄的。

接着大家参照上一篇文章将 MyViewController 加入在U3D之上,请大家看一下我的U3D的工程。

http://www.xuanyusong.com/archives/517

在 OpenEAGL_UnityCallback方法中,在此方法的末尾添加代码:

MyViewController * myView =  [[MyViewController alloc] init];

[sGLViewController.view addSubview:myView.view];

Test.cs 挂在摄像机上 首先截屏一张图存在IOS的沙盒中,当用户点击发送消息时开始调用MyViewConroller中的_AuthoLogin方法进行微薄登录。

using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
void Start ()
Application.CaptureScreenshot("yusong.JPG");
void Update ()
void OnGUI()
if(GUILayout.Button("sendSinaMessage",GUILayout.Width(200),GUILayout.Height(100)))
UIAndDateBinding.AuthLogin();

UIAndDateBinding.cs 这个类负责进行调用IOS前端方法

using UnityEngine;
using System.Runtime.InteropServices;
public class UIAndDateBinding
[DllImport("__Internal")]
    private static extern void _AuthLogin ();
public static void AuthLogin ()
if (Application.platform != RuntimePlatform.OSXEditor)
_AuthLogin();
[DllImport("__Internal")]
    private static extern void _LoginOut ();
public static void LoginOut ()
if (Application.platform != RuntimePlatform.OSXEditor)
_LoginOut();

因为代码比较简单,我就不做过多的说明。然后我们主要来看MyViewController,登录微薄 发送微薄 注销微薄的方式都在这里。

MyViewController.h 没啥东西

//  MyViewController.h
//  Unity-iPhone
//  Created by 雨松MOMO on 12-9-18.
#import <UIKit/UIKit.h>
#import "WBEngine.h"
@interface MyViewController : UIViewController<WBEngineDelegate, UIAlertViewDelegate>

主要的代码都在这里,请大家仔细看喔。

//  MyViewController.m
//  Unity-iPhone
//  Created by 雨松MOMO on 12-9-18.
#import "MyViewController.h"
WBEngine* weiBoEngine;
@interface MyViewController ()
@implementation MyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    return self;
- (void)viewDidLoad
    [super viewDidLoad];
    //初始化微薄客户端
    weiBoEngine = [[WBEngine alloc] initWithAppKey:@"填写你的APPKEY" appSecret:@"填写你的APPSECRET"];
    [weiBoEngine setRootViewController:self];
    [weiBoEngine setDelegate:self];
    [weiBoEngine setRedirectURI:@"http://xuanyusong.com"];
    [weiBoEngine setIsUserExclusive:NO];
    //如果之前登录过让它登出 一般应该让用户手动登出
    if([weiBoEngine isLoggedIn])
      [weiBoEngine logOut];
- (void)viewDidUnload
    [super viewDidUnload];
    // Release any retained subviews of the main view.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
- (void)engineDidLogIn:(WBEngine *)engine
    //微薄登录成功后将进入这里
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *imagePath = [path stringByAppendingPathComponent:@"yusong.JPG"] ;
    NSData *data=[NSData dataWithContentsOfFile:imagePath];
    //从沙盒中将U3D中截取的图像取出
    UIImage *img =[UIImage imageWithData:data];
    //登录成功 直接发送微薄消息
    [weiBoEngine sendWeiBoWithText:@"来自 @雨松MOMO Unity3D For IOS 的分享噢!!" image:img];
- (void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result
    //微薄发送成功调用
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"新浪微博", nil)
                                                         message:NSLocalizedString(@"发送微博成功", nil)
                                                        delegate:nil
                                               cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil];
    [alertView show];
    [alertView release];
- (void)engine:(WBEngine *)engine requestDidFailWithError:(NSError *)error
    //微薄发送失败调用
    //记得每次发微薄如果和上次完全一样,是不会发送成功的
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"新浪微博", nil)
                                                         message:NSLocalizedString(@"发送微博失败", nil)
                                                        delegate:nil
                                               cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil];
    [alertView show];
    [alertView release];
//注册 Unity就是调用这个方法来进行登录微薄的
void _AuthLogin()
    //没有登录的话就登录
    if(![weiBoEngine isLoggedIn])
       [weiBoEngine logIn];
void _LoginOut()
    [weiBoEngine logOut];

发送成功的完整图片。代码我就不上传了,这篇博客也不是很难,仔细看看大家都可以把文字和图片发送在新浪微博中的噢。看了一下表已经不完了,MOMO也得去睡觉了 不然有人会很 很生气 很生气 很生气的,蛤蛤。。

由于我这里的unity版本是3.5 听说在unity4下面会出现无法分享图片的情况, 后来有一个朋友在留言中它解决了这个问题, 我发现还是有朋友会问我这个,所以我还是把他写的文章粘贴过来

单机游戏如果没有服务端,那微博就是一个推广和讨论的好地方。

首先,可以看一下雨松的教程:

http://www.xuanyusong.com/archives/1794

我用的Unity4.0的beta版,发现了不少问题:

一、ViewControl的获得改变了:

sGLViewController 变化为–》UnityGetGLViewController()

二、游戏内截图所放的位置有变化:

Application.persistentDataPath打印出来的是:
/var/mobile/Applications/27F8B3B1-8E33-4196-8610-40D87D6E7F1A/Documents

从IOS中读取的图片路径是:
/var/mobile/Applications/27F8B3B1-8E33-4196-8610-40D87D6E7F1A/Library/Documentation/XX.png

所以我一直无法发出图片。

解决方式是:把路径从Unity3D中传出来。

为了测试,我找了个把截屏的图放到手机相册里的代码。

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class IOSTestSDK : MonoBehaviour {
     [DllImport("__Internal")]
     private static extern void _AuthLogin();
     [DllImport("__Internal")]
     private static extern void _ScreenshotWriteToAlbum(string path);
     public static void ActivateButton()
         if (Application.platform != RuntimePlatform.OSXEditor)
             //_PressButton();
             Debug.Log("Before _AuthLogin");
             _AuthLogin();
             Debug.Log("After _AuthLogin");
     public static void ScreenshotWriteToAlbum(string path)
         _ScreenshotWriteToAlbum(path);
NSString* imgPath;
void _ScreenshotWriteToAlbum(const char* path)
     //imgPath = [NSString stringWithUTF8String:path];
     imgPath = [[NSString alloc] initWithCString:path encoding:NSStringEncodingConversionAllowLossy];
     sendImg = [UIImage imageWithContentsOfFile:[NSString stringWithUTF8String:path]];
     ALAssetsLibrary* library = [[[ALAssetsLibrary alloc] init] autorelease];
     NSMutableDictionary* metadata = [[[NSMutableDictionary alloc] init] autorelease];
     [library writeImageToSavedPhotosAlbum:sendImg.CGImage metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
         if(error)
             NSLog(@"Screenshot error -%@", error);
             NSLog(@"Screenshot taken - %@", error);
-(void)engineDidLogIn:(WBEngine *)engine
     // login success
//    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
//    NSString* path = [paths objectAtIndex:0];
//    NSString* imagePath = [path stringByAppendingPathComponent:@"kitchen.png"];
  //   NSData* data = [NSData dataWithContentsOfFile:imagePath];
//    UIImage* img = [UIImage imageWithData:data];
  //   NSLog(@"path: -%@",imgPath);
     UIImage* img = [UIImage imageWithContentsOfFile:imgPath];
     [weiboEngine sendWeiBoWithText:@"测试IOS发微博" image:img];
 这个是它后面修改的原文地址!!
作者:雨松MOMO
专注移动互联网,Unity3D游戏开发
捐 赠写博客不易,如果您想请我喝一杯星巴克的话?就进来看吧!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK