0

我正在使用 NSURLConection 及其委托方法从在线 TTS api 异步获取数据。这是我要加载的 URL:

http://tts-api.com/tts.mp3?q=hello world

上面的 URL 重定向并给我们一个我需要下载的 MP3 文件。我使用了以下委托方法来下载 mp3 文件:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    if (connection == connectionToTTSAPI) {
        mp3Manager = [NSFileManager defaultManager];
        localPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"hello.mp3"];
        mp3Handler = [NSFileHandle fileHandleForWritingAtPath:localPath];
        if (!mp3Handler) {
            [[NSFileManager defaultManager] createFileAtPath:localPath contents:nil attributes:nil];
            mp3Handler = [NSFileHandle fileHandleForWritingAtPath:localPath];
        }
        @try {
            [mp3Handler seekToEndOfFile];
            [mp3Handler writeData:data];
        }
    }

}

由于我在程序中使用了多个 NSURLConnection,因此我设置了一个 if 条件来识别响应是针对哪个连接的。但我没有得到 mp3 文件,所以我在委托方法中设置了一个断点,发现与 TTS API 的连接从未得到响应。我认为这是因为重定向。在处理一些其他问题时,我已经看到了以下方法的使用,但是我没有在 中找到这样的功能NSURLConnectionDelegate,而且作为 NSURLConnection 的初学者,我不知道如何使用该方法来处理重定向。没有一个结果让我清楚地知道如何使用它。

- (NSURLRequest *)connection: (NSURLConnection *)inConnection
             willSendRequest: (NSURLRequest *)inRequest
            redirectResponse: (NSURLResponse *)inRedirectResponse;
4

1 回答 1

0

对于 iOS,该委托方法在 中定义,NSURLConnectionDataDelegate让您有机会控制如何处理重定向(您可以取消它、更改它或原封不动地返回它)。

在您的情况下,您希望让它请求重定向响应返回的 URL,因此一个简单的实现将是:

- (NSURLRequest *)connection: (NSURLConnection *)inConnection
         willSendRequest: (NSURLRequest *)inRequest
        redirectResponse: (NSURLResponse *)inRedirectResponse {

    return inRequest;
}

我相信这应该是默认行为,所以如果请求没有被处理,问题可能出在其他地方......

于 2013-08-19T06:50:11.813 回答