3

I am following the Spotify SDK tutorial, and trying to make a RN module for my application. This is my SpotifyModule.m code:

#import "SpotifyModule.h"
#import "React/RCTLog.h"
#import "React/RCTBridge.h"


@implementation SpotifyModule


RCT_EXPORT_MODULE()


+ (id)sharedManager {
  static SpotifyModule *sharedManager = nil;
  @synchronized(self) {
    if (sharedManager == nil)
      sharedManager = [[self alloc] init];
  }
  return sharedManager;
}


RCT_EXPORT_METHOD(authenticate:(RCTResponseSenderBlock)callback)
{
  // Your implementation here
  RCTLogInfo(@"authenticate");
  self.auth = [SPTAuth defaultInstance];
  // The client ID you got from the developer site
  self.auth.clientID = @"8fff6cbb84d147e383060be62cec5dfa";
  // The redirect URL as you entered it at the developer site
  self.auth.redirectURL = [NSURL URLWithString:@"my-android-auth://callback"];
  // Setting the `sessionUserDefaultsKey` enables SPTAuth to automatically store the session object for future use.
  self.auth.sessionUserDefaultsKey = @"current session";
  // Set the scopes you need the user to authorize. `SPTAuthStreamingScope` is required for playing audio.
  self.auth.requestedScopes = @[SPTAuthPlaylistReadPrivateScope, SPTAuthUserReadPrivateScope];

  //save the login callback
  SpotifyModule *spotifyModule = (SpotifyModule *)[SpotifyModule sharedManager];
  spotifyModule.loginCallback = callback;

  //setup event dispatcher
  spotifyModule.eventDispatcher = [[RCTEventDispatcher alloc] init];
  [spotifyModule.eventDispatcher setValue:self.bridge forKey:@"bridge"];

  // Start authenticating when the app is finished launching
  dispatch_async(dispatch_get_main_queue(), ^{
    [self startAuthenticationFlow];
  });
}

- (void)startAuthenticationFlow
{
  // Check if we could use the access token we already have
  if ([self.auth.session isValid]) {
    // Use it to log in
      SpotifyModule *spotifyModule = (SpotifyModule *)[SpotifyModule sharedManager];
      NSString *accessToken = self.auth.session.accessToken;
      spotifyModule.loginCallback(@[accessToken]);
  } else {
    // Get the URL to the Spotify authorization portal
    NSURL *authURL = [self.auth spotifyWebAuthenticationURL];
    // Present in a SafariViewController
    self.authViewController = [[SFSafariViewController alloc] initWithURL:authURL];
    UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    [rootViewController presentViewController:self.authViewController animated:YES completion:nil];
  }
}

- (BOOL)  application:(UIApplication *)app
          openURL:(NSURL *)url
          options:(NSDictionary *)options
{
  // If the incoming url is what we expect we handle it
  if ([self.auth canHandleURL:url]) {
    // Close the authentication window
    [self.authViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    self.authViewController = nil;
    // Parse the incoming url to a session object
    [self.auth handleAuthCallbackWithTriggeredAuthURL:url callback:^(NSError *error, SPTSession *session) {
      if (session) {
        // Send auth token
        SpotifyModule *spotifyModule = (SpotifyModule *)[SpotifyModule sharedManager];
        NSString *accessToken = session.accessToken;
        spotifyModule.loginCallback(@[accessToken]);      }
    }];
    return YES;
  }
  return NO;
}

@end

The way I want to use it from the RN end, is call authenticate, with a callback for the access token. I got this working on Android fine.

  Native.authenticate(function(token) {
    store.dispatch(actions.loginSuccess(token));
  });

On iOS, with the above code, I get to the attached screen, and when clicking Ok I get the following error:

SpotiFind[5475:29641] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[SpotifyModule application:openURL:sourceApplication:annotation:]: unrecognized selector sent to class 0x10cb406f8'

So from my minimal ObjectiveC understanding, its trying to call a different method, than the one that the tutorial instructs to implement. Any recommendations on how to make this work ?

If its any relevant, I build against iOS 10, and use the latest Spotify iOS SDK

p.s I realize the name might be against some copyrighting, its just temp for development :)

enter image description here

7
  • Hi @Giannis, did you find a solution to your problem? I'm exactly in the same situation than you. Apr 10, 2017 at 7:58
  • 2
    Did not use tutorial code, this is what I used: pastebin.com/yFKiqV2Z
    – Giannis
    Apr 10, 2017 at 9:26
  • Hey @Giannis, thanks for your snippet ! I'm working with TimothePearce and trying to use your code. I'm an absolute dummy in Objective-C (and so is he), and I can't get the callback to get fired after logging in with Spotify. The Webview opens, I'm displayed the Spotify authorization page, but when I return to the app, nothing happens. I'm testing with a simple console.log(token) and it doesn't work. I've seen from your code that the ObjC callback is supposed to log things in the debugger (like @"authenticate"), but it doesn't happen either. Do you have an idea why ?
    – rgehan
    Apr 13, 2017 at 15:38
  • is [[SPTAuth defaultInstance] setRedirectURL:[NSURL URLWithString:@"app-name://callback"]]; set to the value set in spotify app console ?
    – Giannis
    Apr 13, 2017 at 15:56
  • 1
    Ok so I finally managed to fix my issue. Your code works perfectly, but since my understanding of Objective-C is very minimal, I couldn't manage to make my callbacks work. What you have to do, if you're having the same issue, is create the following method in your AppDelegate.m (and create the prototype in the .h): pastebin.com/BCKmZBkF This method is called when the app is opened through a custom URL scheme. It then calls the corresponding method in the SpotifyModule created by @Giannis.
    – rgehan
    Apr 14, 2017 at 15:24

1 Answer 1

3

Thanks to your tips (in the comments), we managed to make our Spotify authentication work with React-native.

We used the code from your Pastebin to create a reusable module so that nobody has to waste time anymore.

You can find the module here: emphaz/react-native-ios-spotify-sdk

There is a tutorial for the setup and we even created a boilerplate project

Thanks a lot Giannis !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.