10

我正在开发一个 iPhone 应用程序,该应用程序涉及将相机中的完整照片(通常在 1.5 到 2.0 MB 之间)以及它们的缩略图(小得多)上传到 Amazon S3。

缩略图总是成功上传,但有时完整的图像不会,当它们失败时,它们会失败,并显示 POSIX 错误代码 12,即 ENOMEM。但是,我添加了调试代码以在发生错误时打印可用内存量,并且总是有相当多的空闲内存,通常超过 100 MB。

此外,当通过 3G 进行上传时,错误出现的频率更高,而通过 wifi 上传时出现的次数更少——这看起来很奇怪,因为请求下载的次数不多,并且正在上传的文件已经在内存中(我也试过从磁盘流式传输,没有任何改进)。

我尝试使用 NSURLConnection、Foundation CFHTTP* 函数和 ASIHTTPRequest 库上传文件,但无论如何,错误以相同的频率发生。更奇怪的是,我的谷歌搜索显示最终用户有时会从 Safari 获得错误代码 12——我还没有看到任何 iOS 开发人员提到它。我正在使用继承的代码库,所以它可能有问题,但我什至不确定要寻找什么。任何见解将不胜感激!

4

3 回答 3

2

我能够解决此问题的唯一方法是直接使用套接字并手动形成 HTTP 标头。所以我的上传代码目前看起来像这样:

- (void)socketClose
{
    [_inputStream setDelegate:nil];
    [_inputStream close];
    [_inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    SCR_RELEASE_SAFELY(_inputStream);

    [_outputStream setDelegate:nil];
    [_outputStream close];
    [_outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    SCR_RELEASE_SAFELY(_outputStream);

    SCR_RELEASE_SAFELY(_headerBuffer);
}

- (void)sendRequest
{
    [self socketClose];
    SCR_RELEASE_SAFELY(_headerBuffer);

    if (!_shouldCancel)
    {
        NSString *httpMessage = [NSString stringWithFormat:@"POST upload.php HTTP/1.1\r\n"
                                 "Host:"
#ifndef TESTBED
                                 " %@"
#endif
                                 "\r\n"
                                 "User-Agent: MyApp/3.0.0 CFNetwork/534 Darwin/10.7.0\r\n"
                                 "Content-Length: %d\r\n"
                                 "Accept: */*\r\n"
                                 "Accept-Language: en-us\r\n"
                                 "Accept-Encoding: gzip, deflate\r\n"
                                 "Content-Type: application/x-www-form-urlencoded\r\n"
                                 "Connection: keep-alive\r\n\r\n"
                                 "data="
#ifndef TESTBED
                                 , [self.serverUrl host]
#endif
                                 , _bytesToUpload];

        NSString *key = @"data=";
        NSData *keyData = [key dataUsingEncoding:NSASCIIStringEncoding];
        _bytesToUpload -= [keyData length];
        _bytesToUpload = MAX(0, _bytesToUpload);

        _headerBuffer = [[NSMutableData alloc] initWithData:[httpMessage dataUsingEncoding:NSUTF8StringEncoding]];

        _writtenDataBytes = 0;

        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault
                                           , (CFStringRef)[self.serverUrl host]
#ifdef TESTBED
                                           , 8888
#else
                                           , 80
#endif
                                           , (CFReadStreamRef *)(&_inputStream)
                                           , (CFWriteStreamRef *)(&_outputStream));

        [_inputStream setDelegate:self];
        [_outputStream setDelegate:self];

        [_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

        [_inputStream open];
        [_outputStream open];
    }
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
    if (_outputStream == theStream)
    {
        switch (streamEvent)
        {
            case NSStreamEventOpenCompleted:
            {
                [self regenerateTimeoutTimer];
                break;
            }
            case NSStreamEventHasSpaceAvailable:
            {
                SCR_RELEASE_TIMER(_timeoutTimer);
                NSInteger length = _headerBuffer.length;

                if (length > 0)
                {
                    NSInteger written = [_outputStream write:(const uint8_t *)[_headerBuffer bytes] maxLength:length];
                    NSInteger rest = length - written;

                    if (rest > 0)
                    {
                        memmove([_headerBuffer mutableBytes], (const uint8_t *)[_headerBuffer mutableBytes] + written, rest);
                    }

                    [_headerBuffer setLength:rest];
                }
                else
                {
                    const uint8_t *dataBytes = [_data bytes];

                    while ([_outputStream hasSpaceAvailable] && (_writtenDataBytes < _bytesToUpload))
                    {
                        NSInteger written = [_outputStream write:dataBytes
                                                       maxLength:MIN(_dataLength, _bytesToUpload - _writtenDataBytes)];

                        if (written > 0)
                        {
                            _writtenDataBytes += written;
                        }
                    }
                }

                [self regenerateTimeoutTimer];

                break;
            }
            case NSStreamEventErrorOccurred:
            {
                SCR_RELEASE_TIMER(_timeoutTimer);
                [self reportError:[theStream streamError]];                
                break;
            }
            case NSStreamEventEndEncountered:
            {
                SCR_RELEASE_TIMER(_timeoutTimer);
                [self socketClose];
                break;
            }
        }
    }
    else if (_inputStream == theStream)
    {
        switch (streamEvent)
        {
            case NSStreamEventHasBytesAvailable:
            {
                SCR_RELEASE_TIMER(_timeoutTimer);

                /* Read server response here if you wish */

                [self socketClose];

                break;
            }
            case NSStreamEventErrorOccurred:
            {
                SCR_RELEASE_TIMER(_timeoutTimer);
                [self reportError:[theStream streamError]];
                break;
            }
            case NSStreamEventEndEncountered:
            {
                SCR_RELEASE_TIMER(_timeoutTimer);
                [self socketClose];
                break;
            }
        }
    }
}

尽管 ASIHTTPRequest 可以在这里工作,但我们决定摆脱这种依赖关系,既是为了获得性能,也是为了让一切都在我们自己的控制之下。你可以使用 Wireshark 工具来调试这种东西。

于 2011-06-30T11:50:57.490 回答
1

解决此问题的关键是使用流上传文件。使用 NSMutableURLRequest 时,可以使用类似于以下内容的方式来完成:

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBodyStream:[NSInputStream inputStreamWithFileAtPath:filePath]];

使用 ASIHTTPRequest 时,流式传输文件是通过以下方式完成的:

ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
[request setPostBodyFilePath:filePath];
rRequest.shouldStreamPostDataFromDisk = YES;
于 2011-01-29T06:17:45.637 回答
1

已通过将请求 ( NSMutableUrlConnection) 操作与@autorelease{}主函数一起使用解决了此错误。NSPOXIS 只是偶尔出现。

- (void)main
 NSURLConnection* connection;
    @autoreleasepool //urgently needed for 3G upload
    {

        self.currentRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"test.php"]];
        [self.currentRequest setHTTPMethod:@"PUT"];

        [self.currentRequest setHTTPBody:self.data];//inpustStream doesn't work

        connection = [NSURLConnection connectionWithRequest:self.currentRequest delegate:self];
        [connection start];

    }//end autorelease pool

        do 
        {

            [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate distantFuture]];
            if ([self isCancelled])
            {
                connection          = nil;
                isFailed = YES;
                break;
            }
            self.status(statusUpdateMessage);
        } 
        while (!isFailed && !isCompleted);
        [timer invalidate];//test
        timer = nil;

//corresponding of status via blocks
        self.completed(!isFailed);
        self.status(isFailed ? errorMessage : @"Completed");
        if (isFailed)
        {
            self.failed(errorMessage != nil ? errorMessage : @"Undefined error");
        }

        self.data = nil;
        self.currentRequest = nil;

        connection = nil;

}
于 2012-02-10T09:21:07.743 回答