找回密码
 立即注册

IOS中调用新浪微博接口

热度 1已有 763 次阅读2012-11-29 09:42 | 朋友, 新浪微博, 接口, 如何

最近有朋友问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方法进行微薄登录。

01using UnityEngine;
02using System.Collections;
03 
04public class Test : MonoBehaviour {
05 
06    void Start ()
07    {
08        Application.CaptureScreenshot("yusong.JPG");
09    }
10 
11    void Update ()
12    {
13 
14    }
15 
16    void OnGUI()
17    {
18        if(GUILayout.Button("sendSinaMessage",GUILayout.Width(200),GUILayout.Height(100)))
19        {
20 
21            UIAndDateBinding.AuthLogin();
22        }
23 
24    }
25}

 

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

 

01using UnityEngine;
02using System.Runtime.InteropServices;
03 
04public class UIAndDateBinding
05 {
06 
07    [DllImport("__Internal")]
08    private static extern void _AuthLogin ();
09 
10    public static void AuthLogin ()
11    {
12         if (Application.platform != RuntimePlatform.OSXEditor)
13         {
14            _AuthLogin();
15         }
16    }
17 
18    [DllImport("__Internal")]
19    private static extern void _LoginOut ();
20 
21    public static void LoginOut ()
22    {
23         if (Application.platform != RuntimePlatform.OSXEditor)
24         {
25            _LoginOut();
26         }
27    }
28 
29 }

 

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

MyViewController.h 没啥东西

01//
02//  MyViewController.h
03//  Unity-iPhone
04//
05//  Created by 雨松MOMO on 12-9-18.
06//
07//
08 
09#import <UIKit/UIKit.h>
10#import "WBEngine.h"
11 
12@interface MyViewController : UIViewController<WBEngineDelegate, UIAlertViewDelegate>
13{
14 
15}
16@end

 

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

001//
002//  MyViewController.m
003//  Unity-iPhone
004//
005//  Created by 雨松MOMO on 12-9-18.
006//
007//
008 
009#import "MyViewController.h"
010 
011WBEngine* weiBoEngine;
012 
013@interface MyViewController ()
014 
015@end
016 
017@implementation MyViewController
018 
019- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
020{
021    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
022    if (self) {
023 
024    }
025    return self;
026}
027 
028- (void)viewDidLoad
029{
030    [super viewDidLoad];
031 
032    //初始化微薄客户端
033    weiBoEngine = [[WBEngine alloc] initWithAppKey:@"填写你的APPKEY" appSecret:@"填写你的APPSECRET"];
034    [weiBoEngine setRootViewController:self];
035    [weiBoEngine setDelegate:self];
036    [weiBoEngine setRedirectURI:@"http://xuanyusong.com"];
037    [weiBoEngine setIsUserExclusive:NO];
038 
039    //如果之前登录过让它登出 一般应该让用户手动登出
040    if([weiBoEngine isLoggedIn])
041    {
042      [weiBoEngine logOut];
043    }
044 
045}
046 
047- (void)viewDidUnload
048{
049    [super viewDidUnload];
050    // Release any retained subviews of the main view.
051}
052 
053- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
054{
055    return (interfaceOrientation == UIInterfaceOrientationPortrait);
056}
057 
058- (void)engineDidLogIn:(WBEngine *)engine
059{
060    //微薄登录成功后将进入这里
061    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
062    NSString *path = [paths objectAtIndex:0];
063    NSString *imagePath = [path stringByAppendingPathComponent:@"yusong.JPG"] ;
064 
065    NSData *data=[NSData dataWithContentsOfFile:imagePath];
066    //从沙盒中将U3D中截取的图像取出
067    UIImage *img =[UIImage imageWithData:data];
068 
069    //登录成功 直接发送微薄消息
070    [weiBoEngine sendWeiBoWithText:@"来自 @雨松MOMO Unity3D For IOS 的分享噢!!" image:img];
071 
072}
073 
074- (void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result
075{
076    //微薄发送成功调用
077    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"新浪微博", nil)
078                                                         message:NSLocalizedString(@"发送微博成功", nil)
079                                                        delegate:nil
080                                               cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil];
081    [alertView show];
082    [alertView release];
083}
084 
085- (void)engine:(WBEngine *)engine requestDidFailWithError:(NSError *)error
086{
087    //微薄发送失败调用
088    //记得每次发微薄如果和上次完全一样,是不会发送成功的
089    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"新浪微博", nil)
090                                                         message:NSLocalizedString(@"发送微博失败", nil)
091                                                        delegate:nil
092                                               cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil];
093    [alertView show];
094    [alertView release];
095}
096 
097//注册 Unity就是调用这个方法来进行登录微薄的
098void _AuthLogin()
099{
100    //没有登录的话就登录
101    if(![weiBoEngine isLoggedIn])
102    {
103       [weiBoEngine logIn];
104    }
105 
106}
107 
108//登出
109void _LoginOut()
110{
111    [weiBoEngine logOut];
112}
113 
114@end

 

发送成功的完整图片。代码我就不上传了,这篇博客也不是很难,仔细看看大家都可以把文字和图片发送在新浪微博中的噢。看了一下表已经不完了,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); } else { 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]; }
 这个是它后面修改的原文地址!!

路过

雷人
1

握手

鲜花

鸡蛋

刚表态过的朋友 (1 人)

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 立即注册

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-2 09:28 , Processed in 0.065340 second(s), 15 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

返回顶部