multipart / x-mixed-replace with iPhone SDK

时间:2010-03-04 21:21:25

标签: iphone cocoa http sdk nsurlconnection

我正在尝试下载多个图片以响应单个http请求。在服务器端(java)我正在使用oreilly多部分响应,并且在调用didReceiveResponse之后,我在我的iPhone模拟器中的didReceiveData(大约每个图像调用一次)获取数据(对于每个图像也大约调用一次)在我的代表中。 问题是这个...大概有没有人设法用iPhone SDK正确处理multipart / x-mixed-re?如果是,这里最好的策略是什么?我应该玩预期的长度吗?在服务器端?在客户端?我是否应该等到收到所有内容...... mmmh甚至看不到,因为对didReceiveData的调用以随机顺序发生(我问的是picture1,picture2,我有时会收到picture2,picture1,即使订单在服务器端受到尊重!)。我应该在服务器端的图片之间暂时化吗? 或者我应该删除multipart / x-mixed-replace?什么是最容易的呢?

这是很多问题,但我真的被困在这里!谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

我不确定您对图像的最终用途是什么,但是multipart / x-midex-replace内容类型的预期目的是为每个接收到的部分完全替换先前收到的响应。把它想象成视频的帧;一次只显示一张图片,之前的图片将被丢弃。

临时几乎绝不是万无一失的解决方案。特别是在iPhone上你会遇到一种难以想象的各种网络情况,并且依赖于帧之间的幻数延迟可能在某些时候仍会失败。

由于您可以控制服务器,我建议您删除多部分。确保在向服务器发送多个请求时,您不会阻止iPhone应用程序的主线程。使用NSOperations或替代HTTP库(如ASIHTTPRequest)可使您的图像获取操作异步。

答案 1 :(得分:0)

我成功使用此代码。重要的是创建2个缓冲区来接收数据。如果您只使用一个,您将遇到一些双重访问问题(流访问和jpg CODEC访问)和损坏的JPG数据。 不要犹豫,向我询问更多细节。

- (IBAction)startDowload:(id)sender {

    NSURL *url = [NSURL URLWithString:@"http://210.236.173.198/axis-cgi/mjpg/video.cgi?resolution=320x240&fps=5"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

    [req setHTTPMethod:@"GET"];
    /*
    I create 2 NSMutableData buffers. This points is very important.
    I swap them each frame.
    */
    receivedData = [[NSMutableData data] retain];
    receivedData2 = [[NSMutableData data] retain];
    currentData = receivedData;

    urlCon = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    noImg = YES;
    frame = 0;

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse

    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere

    UIImage *_i;
    @try
    {
        _i = [UIImage imageWithData:currentData];
    }
    @catch (NSException * e)
    {
        NSLog(@"%@",[e description]);
    }
    @finally
    {
    }

    CGSize _s = [_i size];
    [imgView setImage:_i];

    [imgView setNeedsDisplay];
    [[self view] setNeedsDisplay];
}   
/*
Buffers swap
*/
    if (currentData == receivedData)
    {
        currentData = receivedData2;        
    }
    else
    {
        currentData = receivedData;     
    }

    [currendData setLength:0];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // append the new data to the currentData (NSData buffer)
    [currendData appendData:data];
}
相关问题