簡體   English   中英

NSData appendData:UIImageJPEGRepresentation()返回nil

[英]NSData appendData: UIImageJPEGRepresentation() returns nil

這讓我抓了很長時間。

我正在准備要發布的UIImage作為HTTP request一部分。 我正在使用以下代碼執行此操作:

[postData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
                        [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"q%@\"; filename=\".jpg\"\r\n" , key] dataUsingEncoding:NSUTF8StringEncoding]];
                        [postData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
                        [postData appendData:[NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)]];
                        [postData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

我遇到的問題是運行這些行后postDatanull

我使用NSLog發現[postData appendData:[NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)]]; 是導致這種情況發生的那條線。 然后,我繼續查看圖像是否有問題。 UIImageJPEGRepresentation(image, 1.0)將大量數據輸出到控制台,並將圖像添加到UIImageView中將顯示我期望的.jpg。

我絕對上當了。 請幫助>。<S

編輯

在下面發生一些崩潰之后,我意識到它肯定是在發布圖像。

NSLog(@"postData = %@",[postData length]);

顯示280861(字節?),但PHP文件帶有<?php print_r($_FILES); ?> <?php print_r($_FILES); ?>返回Array {}

  1. UIImageJPEGRepresentation(image, 1.0)返回一個不能轉換為NSString的NSData對象。 jpeg不包含有效字符。 而且任意數據都不能轉換為有效字符串。

  2. 即使UIImageJPEGRepresentation(image, 1.0)返回nil, [NSData dataWithData:]調用也可以確保您附加到postData的數據不是nil。 [NSData dataWithData:nil]; 返回一個空的NSData實例,而不是nil。

  3. 關於你的答案。 nil不是有效的字符串編碼。 編譯器應該顯示警告,並且您應該在控制台中看到警告“檢測到錯誤的NSStringEncoding值0x0000。假定NSASCIIStringEncoding。將在不久的將來停止這種兼容性映射行為。”。

您不能將postData轉換回NSString。 如果要檢查圖像是否是NSData對象的一部分,可以查看postData的長度。

解決:

[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\nfilename=\"%@.jpeg\"\r\nContent-Type: image/jpeg\r\n\r\n", key,key] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[NSData dataWithData:imageData]];
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

我已經包含的數據之后的第一個換行符似乎已經解決了這個問題

您如何得知postData為空? 請注意,您不能使用以下某些類別/擴展名將其轉換為UTF8字符串。

extension NSData { func to_string(encoding:UInt = NSUTF8StringEncoding) -> String? { return NSString(data:self, encoding:encoding) as? String } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM