![](/img/trans.png)
[英]How to create NSData from a string and an image together and decompile this NSData to a string and an image before
[英]How to check NSData is String or Image
如何檢查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
}
我會問一個設置可以發送沒有元數據的字符串或圖像告訴您哪個設置的問題。
但是,如果您始終收到相同類型的圖像,則可以檢查前幾個字節以查看其是否包含預期的“簽名”。 而且大多數圖像格式在“簽名”中或緊隨其后都將包含一些“非法” Unicode字符,因此您可以確定它不是字符串。
嘗試轉換數據並檢測故障以確定其類型有點笨拙。
一種選擇是嘗試從數據創建NSString
( NSString initWithData:encoding:
。 如果失敗,則嘗試創建UIImage
( UIImage imageWithData:
。 如果失敗,那么您都不會。
另一種選擇是檢查數據長度。 如果您知道將得到的最長字符串永遠不會比得到的最小圖像更多的數據,則此方法有效。
嘗試這個:
UIImage *image= [UIImage imageWithData:imagedata];
if(image != nil){
// correct image
} else{
// incorrect image
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.