Check if NSURL returns 404

后端 未结 4 1656
孤独总比滥情好
孤独总比滥情好 2020-12-02 17:51

I need to check whether a URL (represented by a NSURL) is available or returns 404. What is the best way to achieve that?

I would prefer a way to check this without

4条回答
  •  春和景丽
    2020-12-02 18:20

    I used the answer from woodmantech above, but changed it based on what I have seen on other similar questions here so that it does not download the whole file to see if it exists.

    I changed NSURLRequest to NSMutableURLRequest, and added:

    [request setHTTPMethod:@"HEAD"];
    

    This seems to work fine. I am working on my first app, so no real experience yet. Thanks everyone.

     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
        [request setHTTPMethod:@"HEAD"];
        NSHTTPURLResponse* response = nil;
        NSError* error = nil;
        [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSLog(@"statusCode = %d", [response statusCode]);
    

提交回复
热议问题