我想通过服务器将视频/图像从一台 iPhone 发送到另一台 iPhone。
我已使用 HTTP POST 成功将文件发送到服务器。但问题是我想从服务器接收文件并将其作为数据存储在该设备中以供进一步使用。
任何人都可以建议我一个示例代码来执行相同的操作吗?
您使用 Post 将数据成功发布到服务器。正确的?现在您可以制作一个用于下载图像/视频的 API。获取数据后,将其放入应用程序的文档文件夹中。
关于API,最简单的,只需创建该文件的链接,然后使用 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 个方法:(请阅读 Protocol 和 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 加载它:
NSURL *fileURL = [NSURL fileURLWithPath:strFilePath];
[wvReview loadRequest:[NSURLRequest requestWithURL:fileURL]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)