NSURLConnection从重定向的URL获取数据

问题描述:

我正在使用NSURLConection及其委托方法从联机TTS api异步获取数据。这是我想负荷的网址:NSURLConnection从重定向的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; 
+0

看起来很腥......你怎么处理respons?..也有多少“if”条件? –

+0

如果是让你困惑的if条件,我使用它,因为我使用多个NSURLConnections。 –

+0

我总是使用AFNetworking(http://afnetworking.com)多次请求/下载featured..bcz它给了我很多控制多重请求... –

即委托方法,适用于iOS,在NSURLConnectionDataDelegate定义,让您有机会来控制重定向是如何处理的(你可以取消它,改变它还是原样返回)。

你的情况,你想让它请求URL被重定向响应返回的这么一个简单的实现方式是:

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

    return inRequest; 
} 

我相信这应该是默认的行为了,所以如果请求ISN正在处理,问题可能在其他地方...

+0

抱歉没有得到你..在哪里可以返回这个? –

+0

您提供的NSURLConnectionDelegate方法的实现方法...我将更新答案。 – MattR

+0

不,实际上我没有找到方法' - (*的NSURLRequest)连接:(NSURLConnection的*)inConnection willSendRequest:(*的NSURLRequest)inRequest redirectResponse:(NSURLResponse *)在NSURLConnection的委托inRedirectResponse' 。在哪个委托中声明了该方法? –