ios - 如何检查 NSData 是字符串还是图像

标签 ios

如何检查 NSData 是字符串还是图像数据,我有接收服务器可以得到 2 种类型的数据是字符串和 UIImage 数据。如何检查数据是字符串还是图像数据。提前致谢。

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {
        case NSStreamEventOpenCompleted: {

            NSLog(@"NSStreamEventOpenCompleted");
        } break;
        case NSStreamEventHasBytesAvailable: {
            if(!self.data) {
                self.data = [[NSMutableData alloc] init];
            }
            while (self.networkStream.hasBytesAvailable) {
                uint8_t buf[1024];

                NSInteger len = 0;
                len = [self.networkStream read:buf maxLength:1024];
                if(len>0) {
                    [self.data appendBytes:(const void *)buf length:len];
                    // bytesRead is an instance variable of type NSNumber.
                    self.bytesRead  +=  len; 
                }else{    
                }
            }

            // Event when read input stream done
            if (!self.networkStream.hasBytesAvailable) {

                    [self _didReceiveDataString:self.data];          
            }
        }       
}

最佳答案

同意 rmaddy 的观点。但是在字符串之前检查图像,因为图像数据可能返回一个有效的字符串。

if ([UIImage imageWithData:data])
{
    // get image
}else if ([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding])
{
    // get string        
}

关于ios - 如何检查 NSData 是字符串还是图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27231368/

相关文章:

ios - Swift - 访问 self 以避免将参数传递给函数

ios - swift ,iOS : How to use UIButton to trigger UIAlertController

ios - 无法将类型 'Range<String.Index>'(又名 'Range<String.CharacterView.Index>')的值转换为预期参数类型 'NSRange'(又名 '_NSRange')

ios - 内存在 iOS 模拟器中释放,但在设备 (ipad) 上未释放

iphone - 在 iOS 应用程序中使用预付费点数

ios - 将容器 View 置于最前面

android - 如何为iOS强制抖动设备方向

ios - 如何将我的应用程序提供给一家公司,以便他们可以在不提供我的代码的情况下将其发布到应用程序商店?

ios - 通过 iOS 社交框架在没有帐户的情况下阅读 Twitter/Facebook 信息

ios - 更改按钮标题和颜色时如何防止滞后?