You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C开发iOS Chromecast投屏应用报错求助

Hey there! I’ve helped tons of devs get Chromecast casting up and running in their Objective-C iOS apps, so let’s break this down step by step—including fixing those pesky errors you’re hitting.

完整Objective-C iOS Chromecast投屏实现指南(含错误修复)

一、前期必做准备

First, let’s make sure you’ve got all the foundational pieces in place:

  • Integrate the Google Cast SDK: Use CocoaPods by adding pod 'google-cast-sdk' to your Podfile, then run pod install. If you prefer manual integration, grab the SDK from Google’s official package.
  • Create a Cast Developer App: Head to the Google Cast Developer Console, create a new app, and note down your unique App ID. Don’t forget to add your iOS app’s Bundle ID to the allowed list in the console.
  • Configure Info.plist:
    • Add NSLocalNetworkUsageDescription with a clear message (e.g., "Need access to local network to find Chromecast devices")—iOS 14+ requires this permission to discover local devices.
    • Add a GCKCastReceiverAppID key and set its value to your Cast App ID.

二、核心代码实现

1. Initialize the Cast Context

Start by setting up the Cast framework in your AppDelegate:

#import <GoogleCast/GoogleCast.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Initialize Cast context with your App ID
    GCKCastOptions *castOptions = [[GCKCastOptions alloc] initWithReceiverApplicationID:@"YOUR_CAST_APP_ID"];
    [GCKCastContext setSharedInstanceWithOptions:castOptions];
    
    // Optional: Enable verbose logging for debugging
    [GCKLogger sharedInstance].logLevel = GCKLoggerLevelVerbose;
    [GCKLogger sharedInstance].delegate = self;
    
    return YES;
}

// Optional: Implement logger delegate to capture logs
- (void)logger:(GCKLogger *)logger didLogMessage:(NSString *)message atLevel:(GCKLoggerLevel)level {
    NSLog(@"Cast Log: %@", message);
}

@end

2. Add the Cast Button to Your UI

In your view controller, add the official Cast button and set up session monitoring:

#import <GoogleCast/GoogleCast.h>

@interface VideoViewController () <GCKSessionManagerDelegate>
@property (nonatomic, strong) GCKUICastButton *castButton;
@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Create and position the Cast button
    self.castButton = [[GCKUICastButton alloc] initWithFrame:CGRectMake(20, 70, 24, 24)];
    self.castButton.tintColor = [UIColor systemBlueColor];
    [self.view addSubview:self.castButton];
    
    // Attach session manager delegate to track connection status
    [[GCKCastContext sharedInstance].sessionManager addDelegate:self withQueue:dispatch_get_main_queue()];
}

// Handle successful session start
- (void)sessionManager:(GCKSessionManager *)sessionManager didStartSession:(GCKSession *)session {
    NSLog(@"Connected to Chromecast!");
    [self loadVideoToCast];
}

// Handle session end (with or without error)
- (void)sessionManager:(GCKSessionManager *)sessionManager didEndSession:(GCKSession *)session withError:(NSError *)error {
    if (error) {
        NSLog(@"Cast session ended with error: %@", error.localizedDescription);
    } else {
        NSLog(@"Cast session ended normally");
    }
}

@end

3. Load and Play Media on Chromecast

Implement the method to send your video to the connected Cast device:

- (void)loadVideoToCast {
    // Define media details
    GCKMediaMetadata *metadata = [[GCKMediaMetadata alloc] initWithMetadataType:GCKMediaMetadataTypeMovie];
    [metadata setString:@"Your Video Title" forKey:kGCKMetadataKeyTitle];
    [metadata setString:@"Video Description" forKey:kGCKMetadataKeySubtitle];

    GCKMediaInformation *mediaInfo = [[GCKMediaInformation alloc] initWithContentID:@"https://your-public-video-url.mp4"
                                                                       streamType:GCKMediaStreamTypeBuffered
                                                                      contentType:@"video/mp4"
                                                                         metadata:metadata
                                                                       streamDuration:0
                                                                       customData:nil];

    // Create load request
    GCKMediaLoadRequestData *loadRequest = [[GCKMediaLoadRequestData alloc] initWithMediaInformation:mediaInfo
                                                                                         autoplay:YES
                                                                                       playPosition:0];

    // Send request to Cast device
    GCKRemoteMediaClient *mediaClient = [[GCKCastContext sharedInstance].sessionManager.currentSession remoteMediaClient];
    [mediaClient loadMediaWithRequest:loadRequest completionHandler:^(id _Nullable mediaStatus, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Failed to load media: %@", error.localizedDescription);
        } else {
            NSLog(@"Media started playing on Chromecast!");
        }
    }];
}

三、常见 Errors & Fixes

Error 1: Can’t find any Chromecast devices

  • Double-check that your iOS device and Chromecast are on the same Wi-Fi network.
  • Verify the NSLocalNetworkUsageDescription is present in Info.plist—iOS blocks local network discovery without it.
  • Ensure your Cast App ID is correctly entered and your app’s Bundle ID is registered in the Cast Developer Console.

Error 2: "Not authorized" when connecting to a device

  • If you’re testing, add your Chromecast’s serial number to the "Test Devices" list in the Cast Developer Console.
  • Make sure you’re using a valid, non-expired Cast App ID.

Error 3: Media fails to load with "Invalid media URL"

  • Confirm your video URL is publicly accessible (Chromecast needs direct access—no local-only URLs unless both devices are on the same private network).
  • Use the correct contentType: For MP4, use video/mp4; for HLS streams, use application/vnd.apple.mpegurl.

Error 4: Cast button doesn’t appear

  • Ensure you initialized the GCKCastContext before trying to create the button (do this in AppDelegate).
  • Check the button’s frame—make sure it’s positioned within the visible screen bounds.

四、 Debugging Pro Tips

  • Keep verbose logging enabled (as shown in AppDelegate) to track device discovery, connection attempts, and media loading steps.
  • Use the Google Cast SDK’s built-in debugging tools to inspect session status and error details in real time.

内容的提问来源于stack exchange,提问作者Frederik Frandsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:39:29