如何在iPhone中存储来自服务器的视频/图像文件 [英] How to store a video/image file from a server in iPhone

查看:191
本文介绍了如何在iPhone中存储来自服务器的视频/图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过服务器将视频/图像从一个iPhone发送到另一个iPhone。
我已经使用HTTP POST成功将文件发送到服务器。但问题是我想从服务器接收文件并将其作为数据存储在该设备中以供进一步使用。

I want to send a video/image from one iPhone to another iPhone via a Server. I have successfully sent the file to the server using HTTP POST. But the problem is I want to receive the file from the server and store it in that device as data for further use.

任何人都可以建议我做一个示例代码相同的?

Can any one suggest me a sample code to do the same ?

推荐答案

您可以使用Post将数据成功发布到服务器。对?现在,您可以制作用于下载图像/视频的API。完成数据后,将其放在应用程序的文档文件夹中。
关于API,最简单的,只需创建指向该文件的链接,然后使用NSURLConnection下载。

You use Post to post data to server successfully. Right? Now you can make an API for downloading image/video. When you finish getting data, put it in document folder of your app. About API, for simplest, just create a link to that file, then use NSURLConnection to download.

创建要下载的URL连接:

Create a URL connection to download:

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];

获取保存数据的文件路径:

Get path of file to save data:

strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:strFileName];

你的班级必须采用NSURLConnectionDelegate协议的3种方法:(请阅读有关协议和代表的内容)

Your class must adopt 3 methods of NSURLConnectionDelegate protocol: (please read about Protocol and Delegate)

- (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加载它:

If you want to review you file, use a UIWebview to load it:

NSURL *fileURL = [NSURL fileURLWithPath:strFilePath];
[wvReview loadRequest:[NSURLRequest requestWithURL:fileURL]];

这篇关于如何在iPhone中存储来自服务器的视频/图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆