如何检查所选网址下是否存在jpg / pdf文件?

时间:2018-05-23 05:36:19

标签: ios swift swift3

如果我想检查我的iPhone上是否存在该文件,请使用以下代码:

  let filePath = fileName.path
         let fileManager = FileManager.default
         if fileManager.fileExists (atPath: filePath) {

}

如何检查网址上是否有pdf / jpg / png文件: www.myname.com/files/file1.jpg或www.myname.com/files/file2.pdf等。

我可以请一个这样的功能的例子 - 但是对于互联网网络服务器上的文件吗?

更新

func remoteFileExistsAt(url: URL, completion: @escaping (Bool) -> Void) {
    let checkSession = URLSession.shared
    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"
    request.timeoutInterval = 1.0 // Adjust to your needs

    let task = checkSession.dataTask(with: request) { (data, response, error) -> Void in
        if let httpResp = response as? HTTPURLResponse {
            completion(httpResp.statusCode == 200)
        }
    }
    task.resume()
}

是否可以检查此功能文件是JPG还是PNG类型?如果是这样 - 那么我们也会返回true,如果不是,那么是假的吗?

3 个答案:

答案 0 :(得分:2)

更新

在对评论部分进行讨论之后,代码会更新以更正确的方式工作。

您应该检查mimeType对象的URLResponse,而不是检查图片是否可以表示为UIImageJPEGRepresentation / UIImagePNGRepresentation。因为它并不能保证资源实际上是 jpg / jpeg png

所以mimeType应该是这里需要考虑的最可靠的参数。

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()
}

验证:

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
}

上一个答案:

您可以检查远程数据是否可以表示为UIImageJPEGRepresentationUIImagePNGRepresentation。如果是,您可以说远程文件是 JPEG PNG

试试这个:

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()
}

<强>用法:

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

答案 1 :(得分:0)

如果您想知道服务器上存在该文件,则需要发送HTTP请求并接收响应。

请尝试使用以下代码

func remoteFileExistsAt(url: URL, completion: @escaping (Bool) -> Void) {
    let checkSession = URLSession.shared
    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"
    request.timeoutInterval = 1.0 // Adjust to your needs

    let task = checkSession.dataTask(with: request) { (data, response, error) -> Void in
        if let httpResp = response as? HTTPURLResponse {
            completion(httpResp.statusCode == 200)
        } else {
            completion(false) 
        }
    }
    task.resume()
}

<强>更新

remoteFileExistsAt(url: URL(string: "http://domaind.com/index.php?action=GET_PHOTO&name=102537.jpg&resolution=FHD&lang=PL&region=1")!) { (success) in
    print(success)
}

答案 2 :(得分:0)

这是关于从URL获取数据。如果数据为nil,则文件不存在。

Getting data from an URL in Swift