在Objective-C中调用函数时的逻辑背后

时间:2017-07-16 02:50:12

标签: ios objective-c function delegates

作为Objective-C的初学者,我很难学习如何以及何时调用函数,因为我没有明确说明它。下面是一些用于登录和播放我在网上找到的Spotify SDK中的歌曲的代码。

#import "AppDelegate.h"

@interface AppDelegate ()
@property (nonatomic, strong) SPTAuth *auth;
@property (nonatomic, strong) SPTAudioStreamingController *player;
@property (nonatomic, strong) UIViewController *authViewController;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.auth = [SPTAuth defaultInstance];
    self.player = [SPTAudioStreamingController sharedInstance];

    // The client ID you got from the developer site
    self.auth.clientID = @"5bd669abf2a14fb59839c2c0570843fe";
    // The redirect URL as you entered it at the developer site
    self.auth.redirectURL = [NSURL URLWithString:@"spotlightmusic://returnafterlogin"];
    // 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 = @[SPTAuthStreamingScope];

    // Become the streaming controller delegate
    self.player.delegate = self;

    // Start up the streaming controller.
    NSError *audioStreamingInitError;
    NSAssert([self.player startWithClientId:self.auth.clientID error:&audioStreamingInitError],
             @"There was a problem starting the Spotify SDK: %@", audioStreamingInitError.description);

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

    return YES;
}

- (void)startAuthenticationFlow
{
    // Check if we could use the access token we already have
    if ([self.auth.session isValid]) {
        // Use it to log in
        [self.player loginWithAccessToken:self.auth.session.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];
        [self.window.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) {
                // login to the player
                [self.player loginWithAccessToken:self.auth.session.accessToken];
            }
        }];
        return YES;
    }
    return NO;
}

- (void)audioStreamingDidLogin:(SPTAudioStreamingController *)audioStreaming
{
    [self.player playSpotifyURI:@"spotify:track:3DWOTqMQGp5q75fnVsWwaN" startingWithIndex:0 startingWithPosition:0 callback:^(NSError *error) {
        if (error != nil) {
            NSLog(@"*** failed to play: %@", error);
            return;
        }
    }];
}

@end

我想知道这些函数是如何顺序调用的,具体来说是如何运行audioStreamingDidLogin。

此外,我想知道如何通过来自UI的某种输入从视图控制器调用该函数。

对此逻辑的任何帮助将不胜感激!感谢。

2 个答案:

答案 0 :(得分:1)

您的问题与正在使用的Spotify框架密切相关。这不是Objective-C何时执行某些事情的问题 - 语言具有标准的顺序执行模型 - 而是框架如何进行回调,例如audioStreamingDidLogin,代码并利用线程/ GCD进行并发执行。

首先,您应该阅读Spotify框架文档。

您还可以在每个方法的开头放置一个断点,然后在调试器下运行。当遇到断点时,检查哪个线程已停止并且堆栈跟踪。这应该可以让您了解执行流程和正在使用的并发线程。

HTH

答案 1 :(得分:0)

首先调用UIApplicationDelegate方法application:didFinishLaunchingWithOptions:,然后调用application:openURL:options:

第一个app delegate方法将self设置为AudioStreamingController的delegate。这就是调用audioStreamingDidLogin的方式。你告诉流控制器,“告诉我(self)何时发生有趣的事情”。 (请参阅SPTAudioStreamingControllerDelegate文档了解它可能告诉您的其他内容。)

你可能不会(不应该)直接调用这个函数,特别是如果你有可能在auth完成之前调用它。这样做可能会导致对playSpotifyURI的调用出错。如果您确定用户已通过身份验证,则无需呼叫。只需拨打电话:playSpotifyURI