1

我有一個NSURLConnection連接到我已經做的PHP API。 PHP API以數據響應。由於它是一個動態的應用程序,我這樣做是爲了告訴內容長度:NSURLResponse expectedContentLength -1

ob_start('scAPIHandler');  

function scAPIHandler($buffer){ 

    header('Content-Length: '.strlen($buffer)); 

    return $buffer; 

} 

在API文件的開頭,這一切必要再後來輸出。但是,當

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 

函數觸發時,response.expectedContentLength的值爲-1。當我嘗試連接不到我的PHP API,但在網絡上的一些圖像時,顯示正確的預期內容長度。有什麼辦法可以讓我的PHP API知道NSURLResponse的內容長度嗎?內容長度標題似乎不起作用。

提前致謝!

回答

1

好吧,我已經想通了。我用

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 

    NSDictionary *responseHeaders = ((NSHTTPURLResponse *)response).allHeaderFields; 

    NSLog(@"headers: %@", responseHeaders.description); 

} 

此方法來弄清楚,我的iPhone應用程序被接收的標頭,和我與連接到同一URL時捲曲的印刷頭進行比較。結果發現,捲曲顯示的標題與Objective-C所做的標題之間存在差異。誠然,博格爾斯我的腦海裏了很多,我不知道爲什麼會發生,但我找到了解決辦法:

ob_start('scAPIHandler');  

function scAPIHandler($buffer){ 

    header('Custom-Content-Length: '.strlen($buffer)); 

    return $buffer; 

} 

定製的內容長度也出現在Objective-C,我只是把我的自定義標頭

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 

    self.expectedContentLength = response.expectedContentLength; 
    self.receivedData.length = 0; 

    NSDictionary *responseHeaders = ((NSHTTPURLResponse *)response).allHeaderFields; 

    if(self.expectedContentLength < 0){ 

     // take my own header 

     NSString *actualContentLength = responseHeaders[@"Custom-Content-Length"]; 

     if(actualContentLength && actualContentLength.length > 0){ 

      self.expectedContentLength = actualContentLength.longLongValue; 

     } 

    } 

} 

並覆蓋了預期的內容長度。

相關問題