FBUnityInterface.mm 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. // Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  2. //
  3. // You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
  4. // copy, modify, and distribute this software in source code or binary form for use
  5. // in connection with the web services and APIs provided by Facebook.
  6. //
  7. // As with any software that integrates with the Facebook platform, your use of
  8. // this software is subject to the Facebook Developer Principles and Policies
  9. // [http://developers.facebook.com/policy/]. This copyright notice shall be
  10. // included in all copies or substantial portions of the software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  14. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  15. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  16. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. #import <SafariServices/SafariServices.h>
  19. #import <AuthenticationServices/AuthenticationServices.h>
  20. #import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
  21. #import <FBSDKLoginKit/FBSDKLoginKit-Swift.h>
  22. #import <Foundation/NSJSONSerialization.h>
  23. #include "FBUnityInterface.h"
  24. #include "FBUnitySDKDelegate.h"
  25. #include "FBUnityUtility.h"
  26. #include "FBSDK+Internal.h"
  27. static BOOL _fastAppSwitchEnabled = NO;
  28. @interface FBUnityInterface()
  29. @property (nonatomic, copy) NSString *openURLString;
  30. @end
  31. @implementation FBUnityInterface
  32. #pragma mark Object Initialization
  33. + (FBUnityInterface *)sharedInstance
  34. {
  35. static dispatch_once_t pred;
  36. static FBUnityInterface *shared = nil;
  37. dispatch_once(&pred, ^{
  38. shared = [[FBUnityInterface alloc] init];
  39. shared.shareDialogMode = ShareDialogMode::AUTOMATIC;
  40. });
  41. return shared;
  42. }
  43. + (void)load
  44. {
  45. UnityRegisterAppDelegateListener([FBUnityInterface sharedInstance]);
  46. }
  47. #pragma mark - App (Delegate) Lifecycle
  48. // didBecomeActive: and onOpenURL: are called by Unity's AppController
  49. // because we implement <AppDelegateListener> and registered via UnityRegisterAppDelegateListener(...) above.
  50. - (void)didFinishLaunching:(NSNotification *)notification
  51. {
  52. [[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
  53. didFinishLaunchingWithOptions:notification.userInfo];
  54. }
  55. - (void)didBecomeActive:(NSNotification *)notification
  56. {
  57. }
  58. - (void)onOpenURL:(NSNotification *)notification
  59. {
  60. NSURL *url = notification.userInfo[@"url"];
  61. BOOL isHandledByFBSDK = [[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
  62. openURL:url
  63. sourceApplication:notification.userInfo[@"sourceApplication"]
  64. annotation:notification.userInfo[@"annotation"]];
  65. if (!isHandledByFBSDK) {
  66. [FBUnityInterface sharedInstance].openURLString = [url absoluteString];
  67. }
  68. }
  69. #pragma mark - Implementation
  70. - (void)configureAppId:(const char *)appId
  71. frictionlessRequests:(bool)frictionlessRequests
  72. urlSuffix:(const char *)urlSuffix
  73. {
  74. self.useFrictionlessRequests = frictionlessRequests;
  75. if(appId) {
  76. [FBSDKSettings.sharedSettings setAppID:[FBUnityUtility stringFromCString:appId]];
  77. }
  78. if(urlSuffix && strlen(urlSuffix) > 0) {
  79. [FBSDKSettings.sharedSettings setAppURLSchemeSuffix:[FBUnityUtility stringFromCString:urlSuffix]];
  80. }
  81. NSDictionary *userData = [self getAccessTokenUserData] ?: @{};
  82. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnInitComplete userData:userData requestId:0];
  83. }
  84. - (void)logInWithPublishPermissions:(int) requestId
  85. scope:(const char *)scope
  86. {
  87. [self startLogin:requestId scope:scope isPublishPermLogin:YES];
  88. }
  89. - (void)logInWithReadPermissions:(int) requestId
  90. scope:(const char *)scope
  91. {
  92. [self startLogin:requestId scope:scope isPublishPermLogin:NO];
  93. }
  94. - (void)startLogin:(int) requestId
  95. scope:(const char *)scope
  96. isPublishPermLogin:(BOOL)isPublishPermLogin
  97. {
  98. NSString *scopeStr = [FBUnityUtility stringFromCString:scope];
  99. NSArray *permissions = nil;
  100. if(scope && strlen(scope) > 0) {
  101. permissions = [scopeStr componentsSeparatedByString:@","];
  102. }
  103. void (^loginHandler)(FBSDKLoginManagerLoginResult *,NSError *) = ^(FBSDKLoginManagerLoginResult *result, NSError *error) {
  104. if (error) {
  105. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnLoginComplete error:error requestId:requestId];
  106. return;
  107. } else if (result.isCancelled) {
  108. [FBUnityUtility sendCancelToUnity:FBUnityMessageName_OnLoginComplete requestId:requestId];
  109. return;
  110. }
  111. if ([self tryCompleteLoginWithRequestId:requestId]) {
  112. return;
  113. } else {
  114. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnLoginComplete errorMessage:@"Unknown login error" requestId:requestId];
  115. }
  116. };
  117. FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
  118. [login logInWithPermissions:permissions
  119. fromViewController:nil
  120. handler:loginHandler];
  121. }
  122. - (void)loginWithTrackingPreference:(int)requestId
  123. scope:(const char *)scope
  124. tracking:(const char *)tracking
  125. nonce:(const char *)nonce
  126. {
  127. NSString *scopeStr = [FBUnityUtility stringFromCString:scope];
  128. NSArray *permissions = nil;
  129. if(scope && strlen(scope) > 0) {
  130. permissions = [scopeStr componentsSeparatedByString:@","];
  131. }
  132. NSString *trackingStr = [FBUnityUtility stringFromCString:tracking];
  133. NSString *nonceStr = nil;
  134. if (nonce) {
  135. nonceStr = [FBUnityUtility stringFromCString:nonce];
  136. }
  137. FBSDKLoginConfiguration *config;
  138. if (nonce) {
  139. config = [[FBSDKLoginConfiguration alloc] initWithPermissions:permissions tracking:([trackingStr isEqualToString:@"enabled"] ? FBSDKLoginTrackingEnabled : FBSDKLoginTrackingLimited) nonce:nonceStr appSwitch:_fastAppSwitchEnabled ? FBSDKAppSwitchEnabled : FBSDKAppSwitchDisabled];
  140. } else {
  141. config = [[FBSDKLoginConfiguration alloc] initWithPermissions:permissions tracking:([trackingStr isEqualToString:@"enabled"] ? FBSDKLoginTrackingEnabled : FBSDKLoginTrackingLimited) appSwitch:_fastAppSwitchEnabled ? FBSDKAppSwitchEnabled : FBSDKAppSwitchDisabled];
  142. }
  143. void (^loginHandler)(FBSDKLoginManagerLoginResult *,NSError *) = ^(FBSDKLoginManagerLoginResult *result, NSError *error) {
  144. if (error) {
  145. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnLoginComplete error:error requestId:requestId];
  146. return;
  147. } else if (result.isCancelled) {
  148. [FBUnityUtility sendCancelToUnity:FBUnityMessageName_OnLoginComplete requestId:requestId];
  149. return;
  150. }
  151. if ([self tryCompleteLoginWithRequestId:requestId]) {
  152. return;
  153. } else {
  154. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnLoginComplete errorMessage:@"Unknown login error" requestId:requestId];
  155. }
  156. };
  157. FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
  158. [login logInFromViewController:nil configuration:config completion:loginHandler];
  159. }
  160. - (void)logOut
  161. {
  162. FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
  163. [login logOut];
  164. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnLogoutComplete userData:@{} requestId:0];
  165. }
  166. - (void)appRequestWithRequestId:(int)requestId
  167. message:(const char *)message
  168. actionType:(const char *)actionType
  169. objectId:(const char *)objectId
  170. to:(const char **)to
  171. toLength:(int)toLength
  172. filters:(const char *)filters
  173. data:(const char *)data
  174. title:(const char *)title
  175. {
  176. FBSDKGameRequestContent *content = [[FBSDKGameRequestContent alloc] init];
  177. content.message = [FBUnityUtility stringFromCString:message];
  178. content.actionType = [FBUnityUtility gameRequestActionTypeFromString:[FBUnityUtility stringFromCString:actionType]];
  179. content.objectID = [FBUnityUtility stringFromCString:objectId];
  180. if(to && toLength) {
  181. NSMutableArray *toArray = [NSMutableArray array];
  182. for(int i = 0; i < toLength; i++) {
  183. [toArray addObject:[FBUnityUtility stringFromCString:to[i]]];
  184. }
  185. content.recipients = toArray;
  186. }
  187. content.filters = [FBUnityUtility gameRequestFilterFromString:[FBUnityUtility stringFromCString:filters]];
  188. content.data = [FBUnityUtility stringFromCString:data];
  189. content.title = [FBUnityUtility stringFromCString:title];
  190. FBUnitySDKDelegate *delegate = [FBUnitySDKDelegate instanceWithRequestID:requestId];
  191. NSError *error;
  192. FBSDKGameRequestDialog *dialog = [[FBSDKGameRequestDialog alloc] initWithContent:content delegate:delegate];
  193. dialog.isFrictionlessRequestsEnabled = self.useFrictionlessRequests;
  194. if (![dialog validateWithError:&error]) {
  195. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnAppRequestsComplete error:error requestId:requestId];
  196. }
  197. if (![dialog show]) {
  198. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnAppRequestsComplete errorMessage:@"Failed to show request dialog" requestId:requestId];
  199. }
  200. }
  201. - (void)shareLinkWithRequestId:(int)requestId
  202. contentURL:(const char *)contentURL
  203. contentTitle:(const char *)contentTitle
  204. contentDescription:(const char *)contentDescription
  205. photoURL:(const char *)photoURL
  206. {
  207. FBSDKShareLinkContent *linkContent = [[FBSDKShareLinkContent alloc] init];
  208. NSString *contentUrlStr = [FBUnityUtility stringFromCString:contentURL];
  209. if (contentUrlStr) {
  210. linkContent.contentURL = [NSURL URLWithString:contentUrlStr];
  211. }
  212. [self shareContentWithRequestId:requestId
  213. shareContent:linkContent
  214. dialogMode:[self getDialogMode]];
  215. }
  216. - (void)shareFeedWithRequestId:(int)requestId
  217. toId:(const char *)toID
  218. link:(const char *)link
  219. linkName:(const char *)linkName
  220. linkCaption:(const char *)linkCaption
  221. linkDescription:(const char *)linkDescription
  222. picture:(const char *)picture
  223. mediaSource:(const char *)mediaSource
  224. {
  225. FBSDKShareLinkContent *linkContent = [[FBSDKShareLinkContent alloc] init];
  226. NSString *contentUrlStr = [FBUnityUtility stringFromCString:link];
  227. if (contentUrlStr) {
  228. linkContent.contentURL = [NSURL URLWithString:contentUrlStr];
  229. }
  230. NSMutableDictionary *feedParameters = [[NSMutableDictionary alloc] init];
  231. NSString *toStr = [FBUnityUtility stringFromCString:toID];
  232. if (toStr) {
  233. [feedParameters setObject:toStr forKey:@"to"];
  234. }
  235. NSString *captionStr = [FBUnityUtility stringFromCString:linkCaption];
  236. if (captionStr) {
  237. [feedParameters setObject:captionStr forKey:@"caption"];
  238. }
  239. NSString *sourceStr = [FBUnityUtility stringFromCString:mediaSource];
  240. if (sourceStr) {
  241. [feedParameters setObject:sourceStr forKey:@"source"];
  242. }
  243. [linkContent addParameters:feedParameters bridgeOptions:FBSDKShareBridgeOptionsDefault];
  244. [self shareContentWithRequestId:requestId
  245. shareContent:linkContent
  246. dialogMode:FBSDKShareDialogModeFeedWeb];
  247. }
  248. - (void)shareContentWithRequestId:(int)requestId
  249. shareContent:(FBSDKShareLinkContent *)linkContent
  250. dialogMode:(FBSDKShareDialogMode)dialogMode
  251. {
  252. FBUnitySDKDelegate *delegate = [FBUnitySDKDelegate instanceWithRequestID:requestId];
  253. FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] initWithViewController:nil
  254. content:linkContent
  255. delegate:delegate];
  256. dialog.mode = dialogMode;
  257. NSError *error;
  258. if (![dialog validateWithError:&error]) {
  259. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnShareLinkComplete error:error requestId:requestId];
  260. }
  261. if (![dialog show]) {
  262. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnShareLinkComplete errorMessage:@"Failed to show share dialog" requestId:requestId];
  263. }
  264. }
  265. - (FBSDKShareDialogMode)getDialogMode
  266. {
  267. switch (self.shareDialogMode) {
  268. case ShareDialogMode::AUTOMATIC:
  269. return FBSDKShareDialogModeAutomatic;
  270. case ShareDialogMode::NATIVE:
  271. return FBSDKShareDialogModeNative;
  272. case ShareDialogMode::WEB:
  273. return FBSDKShareDialogModeWeb;
  274. case ShareDialogMode::FEED:
  275. return FBSDKShareDialogModeFeedWeb;
  276. default:
  277. NSLog(@"Unexpected dialog mode: %@", [NSNumber numberWithInt:self.shareDialogMode]);
  278. return FBSDKShareDialogModeAutomatic;
  279. }
  280. }
  281. - (BOOL)tryCompleteLoginWithRequestId:(int) requestId
  282. {
  283. NSMutableDictionary *userData = [[NSMutableDictionary alloc] init];
  284. NSDictionary *accessTokenUserData = [self getAccessTokenUserData];
  285. NSDictionary *authenticationTokenUserData = [self getAuthenticationTokenUserData];
  286. if (accessTokenUserData) {
  287. [userData addEntriesFromDictionary:accessTokenUserData];
  288. }
  289. if (authenticationTokenUserData) {
  290. [userData addEntriesFromDictionary:authenticationTokenUserData];
  291. }
  292. if (userData) {
  293. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnLoginComplete
  294. userData:[userData copy]
  295. requestId:requestId];
  296. return YES;
  297. } else {
  298. return NO;
  299. }
  300. }
  301. - (NSDictionary *)getAccessTokenUserData
  302. {
  303. FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
  304. if (token) {
  305. // Old v3 sdk tokens don't always contain a UserID. If the user ID is null
  306. // treat the token as bad and clear it. These values are all required
  307. // on c# side for initlizing a token.
  308. NSDictionary *userData = [FBUnityUtility getUserDataFromAccessToken:token];
  309. if (userData) {
  310. return userData;
  311. } else {
  312. // The token is missing a required value. Clear the token
  313. [[[FBSDKLoginManager alloc] init] logOut];
  314. }
  315. }
  316. return nil;
  317. }
  318. - (NSDictionary *)getAuthenticationTokenUserData
  319. {
  320. FBSDKAuthenticationToken *token = [FBSDKAuthenticationToken currentAuthenticationToken];
  321. if (token.tokenString && token.nonce) {
  322. return @{
  323. @"auth_token_string": token.tokenString,
  324. @"auth_nonce": token.nonce
  325. };
  326. }
  327. return nil;
  328. }
  329. - (void)refreshLimitedLogin:(int)requestId
  330. fallbackPolicy:(int)fallbackPolicy
  331. {
  332. FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
  333. [login refreshLimitedLoginFromViewController:nil
  334. fallbackPolicy:(FBSDKRefreshFallbackPolicy)fallbackPolicy
  335. completion:^(FBSDKProfile *profile, NSError *error) {
  336. if (error) {
  337. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnRefreshLimitedLoginComplete error:error requestId:requestId];
  338. return;
  339. }
  340. // The refreshed Profile is cached as FBSDKProfile.currentProfile and read on
  341. // the C# side via FB.Mobile.CurrentProfile(). Send back the refreshed
  342. // authentication token so LoginResult can update AuthenticationToken.Current.
  343. NSMutableDictionary *userData = [[NSMutableDictionary alloc] init];
  344. NSDictionary *authenticationTokenUserData = [self getAuthenticationTokenUserData];
  345. if (authenticationTokenUserData) {
  346. [userData addEntriesFromDictionary:authenticationTokenUserData];
  347. }
  348. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnRefreshLimitedLoginComplete
  349. userData:[userData copy]
  350. requestId:requestId];
  351. }];
  352. }
  353. @end
  354. #pragma mark - Actual Unity C# interface (extern C)
  355. extern "C" {
  356. void IOSFBSendViewHierarchy(const char *_tree )
  357. {
  358. Class FBUnityUtility = NSClassFromString(@"FBSDKCodelessIndexer");
  359. [FBUnityUtility performSelector:NSSelectorFromString(@"uploadIndexing:")
  360. withObject:[NSString stringWithUTF8String:_tree]];
  361. }
  362. void IOSFBInit(const char *_appId, bool _frictionlessRequests, const char *_urlSuffix, const char *_userAgentSuffix)
  363. {
  364. // Set the user agent before calling init to ensure that calls made during
  365. // init use the user agent suffix.
  366. [FBSDKSettings.sharedSettings setUserAgentSuffix:[FBUnityUtility stringFromCString:_userAgentSuffix]];
  367. [[FBUnityInterface sharedInstance] configureAppId:_appId
  368. frictionlessRequests:_frictionlessRequests
  369. urlSuffix:_urlSuffix];
  370. [[FBSDKAppEvents shared] setIsUnityInitialized:true];
  371. [[FBSDKAppEvents shared] sendEventBindingsToUnity];
  372. }
  373. void IOSFBEnableProfileUpdatesOnAccessTokenChange(bool enable)
  374. {
  375. [FBSDKProfile enableUpdatesOnAccessTokenChange:enable];
  376. }
  377. void IOSFBLoginWithTrackingPreference(int requestId, const char *scope, const char *tracking, const char *nonce)
  378. {
  379. [[FBUnityInterface sharedInstance] loginWithTrackingPreference:requestId scope:scope
  380. tracking:tracking
  381. nonce:nonce];
  382. }
  383. void IOSFBLogInWithReadPermissions(int requestId,
  384. const char *scope)
  385. {
  386. [[FBUnityInterface sharedInstance] logInWithReadPermissions:requestId scope:scope];
  387. }
  388. void IOSFBLogInWithPublishPermissions(int requestId,
  389. const char *scope)
  390. {
  391. [[FBUnityInterface sharedInstance] logInWithPublishPermissions:requestId scope:scope];
  392. }
  393. void IOSFBLogOut()
  394. {
  395. [[FBUnityInterface sharedInstance] logOut];
  396. }
  397. char* IOSFBCurrentAuthenticationToken()
  398. {
  399. FBSDKAuthenticationToken *token = [FBSDKAuthenticationToken currentAuthenticationToken];
  400. NSString *str = @"";
  401. if (token.tokenString && token.nonce) {
  402. try {
  403. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{
  404. @"auth_token_string": token.tokenString,
  405. @"auth_nonce": token.nonce
  406. } options:NSJSONWritingPrettyPrinted error:nil];
  407. if (jsonData) {
  408. str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  409. }
  410. } catch (NSException *exception) {
  411. NSLog(@"Fail to parse AuthenticationToken");
  412. }
  413. }
  414. const char* string = [str UTF8String];
  415. char* res = (char*)malloc(strlen(string) + 1);
  416. strcpy(res, string);
  417. return res;
  418. }
  419. char* IOSFBCurrentProfile()
  420. {
  421. FBSDKProfile *profile = [FBSDKProfile currentProfile];
  422. NSString *str = @"";
  423. NSMutableDictionary<NSString *, id> *data = [NSMutableDictionary new];
  424. if (profile.userID) {
  425. data[@"userID"] = profile.userID;
  426. }
  427. if (profile.firstName) {
  428. data[@"firstName"] = profile.firstName;
  429. }
  430. if (profile.middleName) {
  431. data[@"middleName"] = profile.middleName;
  432. }
  433. if (profile.lastName) {
  434. data[@"lastName"] = profile.lastName;
  435. }
  436. if (profile.name) {
  437. data[@"name"] = profile.name;
  438. }
  439. if (profile.email) {
  440. data[@"email"] = profile.email;
  441. }
  442. if (profile.imageURL) {
  443. data[@"imageURL"] = profile.imageURL.absoluteString;
  444. }
  445. if (profile.linkURL) {
  446. data[@"linkURL"] = profile.linkURL.absoluteString;
  447. }
  448. if (profile.friendIDs) {
  449. data[@"friendIDs"] = [profile.friendIDs componentsJoinedByString:@","];
  450. }
  451. if (profile.birthday) {
  452. data[@"birthday"] = [NSString stringWithFormat:@"%@", @((time_t)[profile.birthday timeIntervalSince1970])];
  453. }
  454. if (profile.ageRange) {
  455. if (profile.ageRange.min) {
  456. data[@"ageMin"] = profile.ageRange.min.stringValue;
  457. }
  458. if (profile.ageRange.max) {
  459. data[@"ageMax"] = profile.ageRange.max.stringValue;
  460. }
  461. }
  462. if (profile.hometown) {
  463. data[@"hometown_id"] = profile.hometown.id;
  464. data[@"hometown_name"] = profile.hometown.name;
  465. }
  466. if (profile.location) {
  467. data[@"location_id"] = profile.location.id;
  468. data[@"location_name"] = profile.location.name;
  469. }
  470. if (profile.gender) {
  471. data[@"gender"] = profile.gender;
  472. }
  473. try {
  474. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
  475. if (jsonData) {
  476. str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  477. }
  478. } catch (NSException *exception) {
  479. NSLog(@"Fail to parse Profile");
  480. }
  481. const char* string = [str UTF8String];
  482. char* res = (char*)malloc(strlen(string) + 1);
  483. strcpy(res, string);
  484. return res;
  485. }
  486. void IOSFBSetPushNotificationsDeviceTokenString(const char *token)
  487. {
  488. [[FBSDKAppEvents shared] setPushNotificationsDeviceTokenString:[FBUnityUtility stringFromCString:token]];
  489. }
  490. void IOSFBSetShareDialogMode(int mode)
  491. {
  492. [FBUnityInterface sharedInstance].shareDialogMode = static_cast<ShareDialogMode>(mode);
  493. }
  494. void IOSFBAppRequest(int requestId,
  495. const char *message,
  496. const char *actionType,
  497. const char *objectId,
  498. const char **to,
  499. int toLength,
  500. const char *filters,
  501. const char **excludeIds, //not supported on mobile
  502. int excludeIdsLength, //not supported on mobile
  503. bool hasMaxRecipients, //not supported on mobile
  504. int maxRecipients, //not supported on mobile
  505. const char *data,
  506. const char *title)
  507. {
  508. [[FBUnityInterface sharedInstance] appRequestWithRequestId: requestId
  509. message: message
  510. actionType: actionType
  511. objectId: objectId
  512. to: to
  513. toLength: toLength
  514. filters: filters
  515. data: data
  516. title: title];
  517. }
  518. void IOSFBGetAppLink(int requestId)
  519. {
  520. NSURL *url = [NSURL URLWithString:[FBUnityInterface sharedInstance].openURLString];
  521. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnGetAppLinkComplete
  522. userData:[FBUnityUtility appLinkDataFromUrl:url]
  523. requestId:requestId];
  524. [FBUnityInterface sharedInstance].openURLString = nil;
  525. }
  526. void IOSFBShareLink(int requestId,
  527. const char *contentURL,
  528. const char *contentTitle,
  529. const char *contentDescription,
  530. const char *photoURL)
  531. {
  532. [[FBUnityInterface sharedInstance] shareLinkWithRequestId:requestId
  533. contentURL:contentURL
  534. contentTitle:contentTitle
  535. contentDescription:contentDescription
  536. photoURL:photoURL];
  537. }
  538. void IOSFBFeedShare(int requestId,
  539. const char *toId,
  540. const char *link,
  541. const char *linkName,
  542. const char *linkCaption,
  543. const char *linkDescription,
  544. const char *picture,
  545. const char *mediaSource)
  546. {
  547. [[FBUnityInterface sharedInstance] shareFeedWithRequestId:requestId
  548. toId:toId
  549. link:link
  550. linkName:linkName
  551. linkCaption:linkCaption
  552. linkDescription:linkDescription
  553. picture:picture
  554. mediaSource:mediaSource];
  555. }
  556. void IOSFBAppEventsActivateApp()
  557. {
  558. [FBSDKAppEvents.shared activateApp];
  559. }
  560. void IOSFBAppEventsLogEvent(const char *eventName,
  561. double valueToSum,
  562. int numParams,
  563. const char **paramKeys,
  564. const char **paramVals)
  565. {
  566. NSDictionary *params = [FBUnityUtility dictionaryFromKeys:paramKeys values:paramVals length:numParams];
  567. [[FBSDKAppEvents shared] logEvent:[FBUnityUtility stringFromCString:eventName] valueToSum:valueToSum parameters:params];
  568. }
  569. void IOSFBAppEventsLogPurchase(double amount,
  570. const char *currency,
  571. int numParams,
  572. const char **paramKeys,
  573. const char **paramVals)
  574. {
  575. NSDictionary *params = [FBUnityUtility dictionaryFromKeys:paramKeys values:paramVals length:numParams];
  576. [[FBSDKAppEvents shared] logPurchase:amount currency:[FBUnityUtility stringFromCString:currency] parameters:params];
  577. }
  578. void IOSFBAppEventsSetLimitEventUsage(BOOL limitEventUsage)
  579. {
  580. [FBSDKSettings.sharedSettings setIsEventDataUsageLimited:limitEventUsage];
  581. }
  582. void IOSFBAutoLogAppEventsEnabled(BOOL autoLogAppEventsEnabledID)
  583. {
  584. [FBSDKSettings.sharedSettings setAutoLogAppEventsEnabled:autoLogAppEventsEnabledID];
  585. }
  586. void IOSFBAdvertiserIDCollectionEnabled(BOOL advertiserIDCollectionEnabledID)
  587. {
  588. [FBSDKSettings.sharedSettings setAdvertiserIDCollectionEnabled:advertiserIDCollectionEnabledID];
  589. }
  590. BOOL IOSFBAdvertiserTrackingEnabled(BOOL advertiserTrackingEnabled)
  591. {
  592. [FBSDKSettings.sharedSettings setAdvertiserTrackingEnabled:advertiserTrackingEnabled];
  593. return [FBSDKSettings.sharedSettings isAdvertiserTrackingEnabled];
  594. }
  595. BOOL IOSFBDomainErrorEnabled(BOOL domainErrorEnabled)
  596. {
  597. [FBSDKSettings.sharedSettings setIsDomainErrorEnabled:domainErrorEnabled];
  598. return [FBSDKSettings.sharedSettings isDomainErrorEnabled];
  599. }
  600. BOOL IOSFBFastAppSwitchEnabled(BOOL fastAppSwitchEnabled)
  601. {
  602. _fastAppSwitchEnabled = fastAppSwitchEnabled;
  603. return _fastAppSwitchEnabled;
  604. }
  605. char* IOSFBSdkVersion()
  606. {
  607. const char* string = [[FBSDKSettings.sharedSettings sdkVersion] UTF8String];
  608. char* res = (char*)malloc(strlen(string) + 1);
  609. strcpy(res, string);
  610. return res;
  611. }
  612. void IOSFBSetUserID(const char *userID)
  613. {
  614. [[FBSDKAppEvents shared] setUserID:[FBUnityUtility stringFromCString:userID]];
  615. }
  616. void IOSFBOpenGamingServicesFriendFinder(int requestId)
  617. {
  618. [FBSDKFriendFinderDialog
  619. launchFriendFinderDialogWithCompletionHandler:^(BOOL success, NSError * _Nullable error) {
  620. if (!success || error) {
  621. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnFriendFinderComplete error:error requestId:requestId];
  622. } else {
  623. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnFriendFinderComplete
  624. userData:NULL
  625. requestId:requestId];
  626. }
  627. }];
  628. }
  629. void IOSFBCreateGamingContext(int requestID, const char *playerID) {
  630. NSError *error;
  631. NSString *playerIDString = [FBUnityUtility stringFromCString:playerID];
  632. FBUnitySDKDelegate *delegate = [FBUnitySDKDelegate instanceWithRequestID:requestID];
  633. FBSDKCreateContextContent *content = [[FBSDKCreateContextContent alloc] initDialogContentWithPlayerID:playerIDString];
  634. FBSDKContextDialogPresenter *presenter = [[FBSDKContextDialogPresenter alloc] init];
  635. [presenter makeAndShowCreateContextDialogWithContent:content delegate:delegate error:&error];
  636. if (error) {
  637. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnGetTournamentsComplete error:error requestId:requestID];
  638. }
  639. }
  640. void IOSFBSwitchGamingContext(
  641. int requestID,
  642. const char *contextID) {
  643. NSError *error;
  644. NSString *contextIDString = [FBUnityUtility stringFromCString:contextID];
  645. FBUnitySDKDelegate *delegate = [FBUnitySDKDelegate instanceWithRequestID:requestID];
  646. FBSDKSwitchContextContent *content = [[FBSDKSwitchContextContent alloc] initDialogContentWithContextID:contextIDString];
  647. FBSDKContextDialogPresenter *presenter = [[FBSDKContextDialogPresenter alloc] init];
  648. [presenter makeAndShowSwitchContextDialogWithContent:content delegate:delegate error:&error];
  649. if (error) {
  650. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnGetTournamentsComplete error:error requestId:requestID];
  651. }
  652. }
  653. void IOSFBChooseGamingContext(
  654. int requestID,
  655. const char *filter,
  656. int minSize,
  657. int maxSize)
  658. {
  659. FBUnitySDKDelegate *delegate = [FBUnitySDKDelegate instanceWithRequestID:requestID];
  660. FBSDKChooseContextContent *chooseContent = [FBSDKChooseContextContent alloc];
  661. NSString *filterNSString = [NSString stringWithUTF8String:filter];
  662. if ([filterNSString length] == 0) {
  663. chooseContent.filter = FBSDKChooseContextFilterNone;
  664. } else if ([filterNSString isEqualToString:@"NEW_PLAYERS_ONLY"]) {
  665. chooseContent.filter = FBSDKChooseContextFilterNewPlayersOnly;
  666. } else if ([filterNSString isEqualToString:@"INCLUDE_EXISTING_CHALLENGES"]) {
  667. chooseContent.filter = FBSDKChooseContextFilterExistingChallenges;
  668. } else if ([filterNSString isEqualToString:@"NEW_CONTEXT_ONLY"]) {
  669. chooseContent.filter = FBSDKChooseContextFilterNewContextOnly;
  670. }
  671. if (minSize > 0) {
  672. chooseContent.minParticipants = minSize;
  673. }
  674. if (maxSize > 0) {
  675. chooseContent.maxParticipants = maxSize;
  676. }
  677. FBSDKContextDialogPresenter *presenter = [[FBSDKContextDialogPresenter alloc] init];
  678. [presenter makeAndShowChooseContextDialogWithContent:chooseContent delegate:delegate];
  679. }
  680. void IOSFBGetCurrentGamingContext(int requestID)
  681. {
  682. FBSDKGamingContext *currentContext = [FBSDKGamingContext currentContext];
  683. if (currentContext) {
  684. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnGetCurrentGamingContextComplete
  685. userData:@{@"contextId":[currentContext identifier]}
  686. requestId:requestID];
  687. } else {
  688. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnGetCurrentGamingContextComplete
  689. userData:NULL
  690. requestId:requestID];
  691. }
  692. }
  693. void IOSFBSetDataProcessingOptions(
  694. const char** options,
  695. int numOptions,
  696. int country,
  697. int state) {
  698. NSMutableArray<NSString*>* array = [[NSMutableArray alloc] init];
  699. for (int i = 0; i < numOptions; i++) {
  700. NSString* option = [FBUnityUtility stringFromCString:options[i]];
  701. if (option) {
  702. [array addObject:option];
  703. }
  704. }
  705. [FBSDKSettings.sharedSettings setDataProcessingOptions:array country:country state:state];
  706. }
  707. void IOSFBGetTournaments(int requestID)
  708. {
  709. FBSDKTournamentFetcher *fetcher = [[FBSDKTournamentFetcher alloc] init];
  710. [fetcher fetchTournamentsWithCompletionHandler:^(NSArray<FBSDKTournament *> * tournaments, NSError * error) {
  711. if (error) {
  712. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnGetTournamentsComplete error:error requestId:requestID];
  713. }
  714. NSMutableDictionary *userData = [NSMutableDictionary new];
  715. for (FBSDKTournament *tournament in tournaments) {
  716. userData[tournament.identifier] = [tournament toDictionary];
  717. }
  718. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnGetTournamentsComplete
  719. userData:userData
  720. requestId:requestID];
  721. }];
  722. }
  723. void IOSFBUpdateTournament(const char *tournamentID, int score, int requestID)
  724. {
  725. FBSDKTournamentUpdater *updater = [[FBSDKTournamentUpdater alloc] init];
  726. [updater updateWithTournamentID:[NSString stringWithUTF8String:tournamentID]
  727. score:score
  728. completionHandler:^(BOOL success, NSError * _Nullable error) {
  729. if (!success || error) {
  730. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnUpdateTournamentComplete error:error requestId:requestID];
  731. } else {
  732. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnUpdateTournamentComplete
  733. userData:NULL
  734. requestId:requestID];
  735. }
  736. }];
  737. }
  738. void IOSFBUpdateAndShareTournament(const char *tournamentID, int score, int requestID)
  739. {
  740. NSError *error;
  741. FBUnitySDKDelegate *delegate = [FBUnitySDKDelegate instanceWithRequestID:requestID];
  742. FBSDKShareTournamentDialog *dialog = [[FBSDKShareTournamentDialog alloc] initWithDelegate: delegate];
  743. [dialog showWithScore:score tournamentID:[NSString stringWithUTF8String:tournamentID] error:&error];
  744. if (error) {
  745. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnGetTournamentsComplete error:error requestId:requestID];
  746. }
  747. }
  748. void IOSFBCreateAndShareTournament(
  749. int initialScore,
  750. const char *title,
  751. int sortOrder,
  752. int scoreFormat,
  753. long endTime,
  754. const char *payload,
  755. int requestID)
  756. {
  757. NSError *error;
  758. FBUnitySDKDelegate *delegate = [FBUnitySDKDelegate instanceWithRequestID:requestID];
  759. FBSDKShareTournamentDialog *dialog = [[FBSDKShareTournamentDialog alloc] initWithDelegate: delegate];
  760. NSString *payloadString;
  761. if (payload) {
  762. payloadString = [NSString stringWithUTF8String:payload];
  763. }
  764. [dialog showWithInitialScore:initialScore
  765. title:[NSString stringWithUTF8String:title]
  766. endTime:[NSDate dateWithTimeIntervalSince1970: endTime]
  767. scoreType:scoreFormat
  768. sortOrder:sortOrder
  769. payload:payloadString
  770. error: &error];
  771. if (error) {
  772. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnGetTournamentsComplete error:error requestId:requestID];
  773. }
  774. }
  775. void IOSFBUploadImageToMediaLibrary(
  776. int requestId,
  777. const char *caption,
  778. const char *imageUri,
  779. bool shouldLaunchMediaDialog)
  780. {
  781. NSString *captionString = [FBUnityUtility stringFromCString:caption];
  782. NSString *imageUriString = [FBUnityUtility stringFromCString:imageUri];
  783. UIImage *image = [UIImage imageWithContentsOfFile:imageUriString];
  784. FBSDKGamingImageUploaderConfiguration *config =
  785. [[FBSDKGamingImageUploaderConfiguration alloc]
  786. initWithImage:image
  787. caption:captionString
  788. shouldLaunchMediaDialog:shouldLaunchMediaDialog ? YES: NO];
  789. [FBSDKGamingImageUploader
  790. uploadImageWithConfiguration:config
  791. andResultCompletion:^(BOOL success, id result, NSError * _Nullable error) {
  792. if (!success || error) {
  793. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnUploadImageToMediaLibraryComplete
  794. error:error
  795. requestId:requestId];
  796. } else {
  797. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnUploadImageToMediaLibraryComplete
  798. userData:@{@"id":result[@"id"]}
  799. requestId:requestId];
  800. }
  801. }];
  802. }
  803. void IOSFBUploadVideoToMediaLibrary(int requestId,
  804. const char *caption,
  805. const char *videoUri)
  806. {
  807. NSString *captionString = [FBUnityUtility stringFromCString:caption];
  808. NSString *videoUriString = [FBUnityUtility stringFromCString:videoUri];
  809. NSURL *videoURL = [NSURL fileURLWithPath:videoUriString];
  810. FBSDKGamingVideoUploaderConfiguration *config =
  811. [[FBSDKGamingVideoUploaderConfiguration alloc]
  812. initWithVideoURL:videoURL
  813. caption:captionString];
  814. [FBSDKGamingVideoUploader
  815. uploadVideoWithConfiguration:config
  816. andResultCompletion:^(BOOL success, id result, NSError * _Nullable error) {
  817. if (!success || error) {
  818. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnUploadVideoToMediaLibraryComplete
  819. error:error
  820. requestId:requestId];
  821. } else {
  822. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnUploadVideoToMediaLibraryComplete
  823. userData:@{@"id":result[@"id"]}
  824. requestId:requestId];
  825. }
  826. }];
  827. }
  828. char* IOSFBGetUserID()
  829. {
  830. NSString *userID = [[FBSDKAppEvents shared] userID];
  831. if (!userID) {
  832. return NULL;
  833. }
  834. const char* string = [userID UTF8String];
  835. char* res = (char*)malloc(strlen(string) + 1);
  836. strcpy(res, string);
  837. return res;
  838. }
  839. void IOSFBFetchDeferredAppLink(int requestId)
  840. {
  841. [FBSDKAppLinkUtility fetchDeferredAppLink:^(NSURL *url, NSError *error) {
  842. if (error) {
  843. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnFetchDeferredAppLinkComplete error:error requestId:requestId];
  844. return;
  845. }
  846. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnFetchDeferredAppLinkComplete
  847. userData:[FBUnityUtility appLinkDataFromUrl:url]
  848. requestId:requestId];
  849. }];
  850. }
  851. void IOSFBRefreshCurrentAccessToken(int requestId)
  852. {
  853. FBSDKGraphRequestCompletion completion = ^(id<FBSDKGraphRequestConnecting> connection, id result, NSError *error) {
  854. if (error) {
  855. [FBUnityUtility sendErrorToUnity:FBUnityMessageName_OnRefreshCurrentAccessTokenComplete error:error requestId:requestId];
  856. return;
  857. }
  858. [FBUnityUtility sendMessageToUnity:FBUnityMessageName_OnRefreshCurrentAccessTokenComplete
  859. userData:[FBUnityUtility getUserDataFromAccessToken:[FBSDKAccessToken currentAccessToken]]
  860. requestId:requestId];
  861. };
  862. [FBSDKAccessToken refreshCurrentAccessTokenWithCompletion: completion];
  863. }
  864. void IOSFBRefreshLimitedLogin(int requestId, int fallbackPolicy)
  865. {
  866. [[FBUnityInterface sharedInstance] refreshLimitedLogin:requestId fallbackPolicy:fallbackPolicy];
  867. }
  868. }