ios - 我无法初始化 NSInputStream

标签 ios iphone cocoa-touch nsstream nsinputstream

请帮助我,我快疯了。 我需要创建一个 NSInputStream,这样我就可以通过 wifi 从摄像头读取实时预览。 liveViewStream 是一个 NSInputStream-Instance-Variable,在我的实现中声明如下:

@implementation MKSonyCamHandler{
    NSInputStream *liveViewStream;
}

liveViewURL 是一个有效的 URL,当我连接到相机的网络时,我可以在浏览器中打开它(尽管我认为这没有任何区别)。我已经检查过它是否存在,不是 nil 并且包含我期望的值。 但是当我这样做时:

liveViewStream = [[NSInputStream alloc] initWithURL:liveViewURL];
DLog(@"%@", liveViewStream);

alloc-init 命令后的 DLog 每次都会记录“(null)”,如果我知道为什么我会被诅咒。有人遇到过这个吗?我在这里遗漏了一些明显的东西吗? 这是我第一次使用 NSStreams,是否有一个常见的陷阱可能是原因? 文档明确指出 -initWithURL:

Creates and returns an initialized NSInputStream object that reads data from
the file at a given URL.

有什么想法吗?我开始觉得这里真的很愚蠢。

编辑:我正在使用 ARC。

最佳答案

谢谢大家,我找到了。

问题是,我的问题已经有了我需要的所有线索,因为就像我写的那样,NSStream 的 -initWithURL: 将

Create and return an initialized NSInputStream object that reads data from
the file at a given URL.

我没有看到的是,这仅适用于本地资源。如果你想要一个远程主机,(我有一个无线网络连接)你需要使用其他东西,因为,我在这里再次引用文档:

The NSStream class does not support connecting to a remote host on iOS.

好吧,为了它的值(value),你需要创建一个CFReadStreamRef和一个CFWriteStreamRef,然后使用魔术函数CFStreamCreatePairWithSocketToHost来连接他们给你的主人。之后,您可以将它们分别转换为 NSInputStreamNSOutputStream,它们将按预期工作。这是文档中的代码示例:

    CFReadStreamRef readStream;

    CFWriteStreamRef writeStream;

    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[website host], 80, &readStream, &writeStream);



    NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;

    NSOutputStream *outputStream = (__bridge_transfer NSOutputStream *)writeStream;

    [inputStream setDelegate:self];

    [outputStream setDelegate:self];

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [inputStream open];

    [outputStream open];

希望这在某些时候对某人有所帮助。

@leparlon:

我赞成你的回答,因为你肯定在正确的轨道上,建议使用 initWithData。

关于ios - 我无法初始化 NSInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20571069/

相关文章:

ios - 仅当来自服务器的数据快速加载到第一个 View Controller 的核心数据中时,如何运行第二个 View Controller

ios - UITableView 字母顺序有问题

iphone - 如何跳过压缩一张 PNG?

ios - 可以在单独的线程中使用 NSFetchedResultsController 来加载 TableViewCells 吗?

objective-c - 如何将值传递给@protocol

iOS调查应用程序

ios - 在运行时快速更改类

html - 如何从 iOS UILabel 对象中的 NSAttributedString(从 HTML 转换而来)中消除多余的换行符?

iphone - 当成功 block 启动时,__block 弱崩溃

iphone - XCode静态分析器: Analyzer skipped this file due to parse errors