Simpliest Solution to Check If File Exists on a Webserver. (Swift)

Simpliest solution to check if File exists on a webserver. (Swift)

Checking if a resource exists on a server requires sending a HTTP
request and receiving the response. TCP communication can take some
amount of time, e.g. if the server is busy, some router between the
client and the server does not work
correctly, the network is down etc.

That's why asynchronous requests are always preferred. Even if you think
that the request should take only milliseconds, it might sometimes be
seconds due to some network problems. And – as we all know – blocking
the main thread for some seconds is a big no-no.

All that being said, here is a possible implementation for a
fileExists() method. You should not use it on the main thread,
you have been warned!

The HTTP request method is set to "HEAD", so that the server sends
only the response header, but no data.

func fileExists(url : NSURL!) -> Bool {

let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = "HEAD"
req.timeoutInterval = 1.0 // Adjust to your needs

var response : NSURLResponse?
NSURLConnection.sendSynchronousRequest(req, returningResponse: &response, error: nil)

return ((response as? NSHTTPURLResponse)?.statusCode ?? -1) == 200
}

IOS: Check existence of remote file

**Use this function below to check whether file exists at specified url**

+(void)checkWhetherFileExistsIn:(NSURL *)fileUrl Completion:(void (^)(BOOL success, NSString *fileSize ))completion
{
//MAKING A HEAD REQUEST
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileUrl];
request.HTTPMethod = @"HEAD";
request.timeoutInterval = 3;

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if (connectionError == nil) {
if ((long)[httpResponse statusCode] == 200)
{
//FILE EXISTS

NSDictionary *dic = httpResponse.allHeaderFields;
NSLog(@"Response 1 %@",[dic valueForKey:@"Content-Length"]);
completion(TRUE,[dic valueForKey:@"Content-Length"]);
}
else
{
//FILE DOESNT EXIST
NSLog(@"Response 2");
completion(FALSE,@"");
}
}
else
{
NSLog(@"Response 3");
completion(FALSE,@"");
}

}];
}

How to check if a file exists in the Documents directory in Swift?

Swift 4.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
} else {
print("FILE PATH NOT AVAILABLE")
}

Swift 3.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)

let filePath = url.appendingPathComponent("nameOfFileHere").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}

Swift 2.x version, need to use URLByAppendingPathComponent

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}

How can you determine if a file exists within the app bundle?

[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];

Android; Check if file exists without creating a new one

Your chunk of code does not create a new one, it only checks if its already there and nothing else.

File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.

How to check if Swift URL is directory

The name says it all "hasDirectoryPath". It doesn't state that the URL is a directory and it exists. It says that it has a directory path. To make sure that the URL is a directory you can get URL ResourceKey isDirectoryKey:

extension URL {
var isDirectory: Bool {
(try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
}
}

Swift download image if it exists on server

First off, I would switch over to using a NSURLSession. It gives you more options, such as background downloads, and NSURLConnection is deprecated.

For the image issue you are just checking for data in your completion handler. Since HTTP is text based, even an error is data coming back. You should be checking the response header instead to see if your request was responded to with a 404 or whatever error code your web service is returning. Then you know if you should continue with downloading the image or not.

How to check if the jpg / pdf file exists under the selected url?

Updated:

After the discussion on the comments section, the code is updated to work in more correct way.

You should check for the mimeType of the URLResponse object rather than checking whether the image could be represented as UIImageJPEGRepresentation/UIImagePNGRepresentation or not. Because it doesn't guarantee that the resource is actually a jpg/jpeg or png.

So the mimeType should be the most reliable parameter that needs to considered here.

enum MimeType: String {
case jpeg = "image/jpeg"
case png = "image/png"
}

func remoteResource(at url: URL, isOneOf types: [MimeType], completion: @escaping ((Bool) -> Void)) {
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let response = response as? HTTPURLResponse, response.statusCode == 200, let mimeType = response.mimeType else {
completion(false)
return
}
if types.map({ $0.rawValue }).contains(mimeType) {
completion(true)
} else {
completion(false)
}
}
task.resume()
}

Verify with this:

let jpegImageURL = URL(string: "https://vignette.wikia.nocookie.net/wingsoffire/images/5/54/Panda.jpeg/revision/latest?cb=20170205005103")!
remoteResource(at: jpegImageURL, isOneOf: [.jpeg, .png]) { (result) in
print(result) // true
}

let pngImageURL = URL(string: "https://upload.wikimedia.org/wikipedia/commons/6/69/Giant_panda_drawing.png")!
remoteResource(at: pngImageURL, isOneOf: [.jpeg, .png]) { (result) in
print(result) //true
}

let gifImageURL = URL(string: "https://media1.tenor.com/images/f88f6514b1a800bae53a8e95b7b99172/tenor.gif?itemid=4616586")!
remoteResource(at: gifImageURL, isOneOf: [.jpeg, .png]) { (result) in
print(result) //false
}

Previous Answer:

You can check if the remote data can be represented as UIImageJPEGRepresentation or UIImagePNGRepresentation. If yes, you can say that remote file is either JPEG or PNG.

Try this:

func remoteResource(at url: URL, isImage: @escaping ((Bool) -> Void)) {
let request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let data = data, let image = UIImage(data: data) {
if let _ = UIImageJPEGRepresentation(image, 1.0) {
isImage(true)
} else if let _ = UIImagePNGRepresentation(image) {
isImage(true)
} else {
isImage(false)
}

} else {
isImage(false)
}
}
task.resume()
}

Usage:

let imageURL = URL(string: "http://domaind.com/index.php?action=GET_PHOTO&name=102537.jpg&resolution=FHD&lang=PL®ion=1")!
remoteResource(at: imageURL) { (isImage) in
print(isImage) // prints true for your given link
}

Check if file exists on remote server and various drive

In UNC paths, drives are represented by a $. That is, D$. Try this:

System.IO.File.Exists(@"\\ourvideoserver\D$\pcode\videofile_name.mp4")


Related Topics



Leave a reply



Submit