我想从远程网址下载视频并将其保存到iPhone应用中的文件中。 我知道视频链接有效,因为我从AVPlayer使用它,但是,我无法下载它。响应始终为(null)。
以下代码有什么问题?
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:someURLString]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:someFilePath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Successfully downloaded file to %@", [NSURL fileURLWithPath:someFilePath]);
NSLog(@"THE RESPONSE: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[operation start];
更新
我注释掉了operation.outputStream行,这次我收到了回复。这是否意味着文件路径有问题?
答案 0 :(得分:0)
只需创建指向该文件的链接,然后使用NSURLConnection进行下载。
创建要下载的URL连接:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:strFileUrl]]; //strFileURL is url of your video/image
NSURLConnection *conection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO] autorelease];
[conec start];
[request release];
获取保存数据的文件路径:
strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:strFileName];
你的班级必须采用NSURLConnectionDelegate协议的3种方法:(请阅读有关协议和代表的内容)
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// create
[[NSFileManager defaultManager] createFileAtPath:strFilePath contents:nil attributes:nil];
file = [[NSFileHandle fileHandleForUpdatingAtPath:strFilePath] retain];// read more about file handle
if (file) {
[file seekToEndOfFile];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receivedata
{
//write each data received
if( receivedata != nil){
if (file) {
[file seekToEndOfFile];
}
[file writeData:receivedata];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//close file after finish getting data;
[file closeFile];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//do something when downloading failed
}
如果要查看您的文件,请使用UIWebview加载它:
NSURL *fileURL = [NSURL fileURLWithPath:strFilePath];
[wvReview loadRequest:[NSURLRequest requestWithURL:fileURL]];
答案 1 :(得分:0)
这就是出错了。
我正在使用视频的网址,并作为文件路径的一部分。
为什么这是错的?它有反斜杠,所以我认为iOS很混乱。
获得的经验教训:确保添加到目录中以创建文件的字符串没有反斜杠。
我希望这可以帮助那些犯这个愚蠢错误的人。 :P