Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 检查URL文件是否存在_Iphone_Xcode_Url_Mpmovieplayercontroller - Fatal编程技术网

Iphone 检查URL文件是否存在

Iphone 检查URL文件是否存在,iphone,xcode,url,mpmovieplayercontroller,Iphone,Xcode,Url,Mpmovieplayercontroller,我想知道如何在不先下载数据的情况下检查服务器上是否存在文件 我有大约30个不同的对象,其中一些连接到服务器上的电影。目前,我使用NSData控制URL是否存在,然后显示电影,或者是否不存在,然后提醒用户该对象没有视频。我目前使用的代码是: NSString *fPath = [[NSString alloc] initWithFormat:@"http://www.myserver/%@", [rows idNr]]; NSURL *videoURL = [NSURL URLWithString

我想知道如何在不先下载数据的情况下检查服务器上是否存在文件

我有大约30个不同的对象,其中一些连接到服务器上的电影。目前,我使用NSData控制URL是否存在,然后显示电影,或者是否不存在,然后提醒用户该对象没有视频。我目前使用的代码是:

NSString *fPath = [[NSString alloc] initWithFormat:@"http://www.myserver/%@", [rows idNr]];
NSURL *videoURL = [NSURL URLWithString:fPath];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];

url = [NSURL URLWithString:fPath];
[fPath release];

if (videoData) {
    [self performSelectorOnMainThread:@selector(playVideo:) withObject:url waitUntilDone:NO];
} else {
    NSLog(@"videodata false");
    errorLabel.hidden = NO;
    activityView.hidden = YES;
}
“rows idNr”是对象的名称。这个方法正是我想要的,但问题是,使用NSData,它首先“下载”文件,当URL验证为文件时,电影将再次加载到movieplayer中。这意味着加载文件需要两倍的时间


建议?

您可以通过FTP服务器使用size命令检查文件大小来完成此操作。如果文件大小为零,则文件根本不存在

NSError *err;
if ([videoURL checkResourceIsReachableAndReturnError:&err] == NO)
   NSLog(@"wops!");
检查如何执行此操作


当然,您也可以通过将
NSURLRequest
NSURLConnection
一起使用,检查状态是否为200(成功)或404(失败)。404状态不一定是文件不存在,也可能是无法检索文件

我花了一段时间才找到我的答案。引述:

您可以使用发送HTTP头请求 (有一种方法叫做
setHTTPMethod
)。你也会得到同样的结果 响应头与GET相同,但您不必下载整个响应头 资源机构。如果要同步获取数据,请使用
nsurl连接的方法


通过这种方式,您将知道文件是否存在,如果存在,则不会下载所有文件。

使用所需的url请求创建一个URLConnecion对象,并将
NSURLConnectionLegate
添加到.h文件中,就像我想检查“yoururl”是否存在一样,然后您需要做的是

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString: @"http://www.google.com"]];

NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
然后,您可以在
nsurlconnectionelegate

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    int code = [(NSHTTPURLResponse *)response statusCode];
    if (code == 404)
    {
        // website not found
        // do your stuff according to your need 
    }
} 

您还可以找到各种状态代码。

以下是接受答案的代码(为方便起见):

如何打电话

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"HEAD"];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

那是我的错。您可以尝试连接到URL并检查响应代码,如本问题中所述:和的可能重复。