我必须将一些Objective-C代码翻译成Swift,我在Swift中是一个新手,在Objective-C中是一个完整的Noob。
这条线路造成了麻烦:
MyStreamingVideoView* view = (MyStreamingVideoView*)self.view;
我用它翻译了它:
let view = self.view as! MyStreamingVideoView
但是我收到了这个错误:
Could not cast value of type 'UIView' (0x19f802608) to 'MyStreamingVideoView' (0x1001ba938)
我要翻译的代码是多一点,所以我粘贴整个代码并告诉你我是如何翻译的:
目标C:
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#import "ViewController.h"
#import "RTPReceiver.h"
#import "MyStreamingVideoView.h"
#define LISTEN_PORT 5000
@interface ViewController ()
@property (strong) RTPReceiver* receiver;
@end
@implementation ViewController
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSString* ip = [self findLocalWifiIp];
NSLog(@"local IP: %@",ip);
MyStreamingVideoView* view = (MyStreamingVideoView*)self.view;
view.waiting = YES;
self.receiver = [[RTPReceiver alloc] initWithLocalIp:ip listenPort:LISTEN_PORT];
self.receiver.delegate = view;
[view setNeedsDisplay];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(decodingFailed:)
name:AVSampleBufferDisplayLayerFailedToDecodeNotification
object:self.view.layer];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
self.receiver = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void) decodingFailed:(NSNotification*)notification {
NSLog(@"decoding failed: %@",notification.userInfo[AVSampleBufferDisplayLayerFailedToDecodeNotificationErrorKey]);
}
@end
Swift Code:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
//ERROR WITH THIS LINE
self.receiver = nil
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let ip = RTPTools().findLocalWifiIp()
print("local IP: \(ip)")
//ERROR WITH THIS LINE
let view = self.view as! MyStreamingVideoView
view.waiting = true
self.receiver = RTPReceiver(localIp: ip, listenPort: 5000)
self.receiver.delegate = view
view.setNeedsDisplay()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MasterViewController.decodingFailed(_:)), name: AVSampleBufferDisplayLayerFailedToDecodeNotification, object: self.view.layer)
}
func decodingFailed(notification: NSNotification) {
print("decoding failed: ")
}
感谢您的帮助。