Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

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

There are a lot of discussion about this and I understand the solution to use the delegate method and check the response "404":

var request : NSURLRequest = NSURLRequest(URL: url)

var connection : NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//...
}

But I would like to have a simple solution like:

var exists:Bool=fileexists(sURL);

Because I will have a lot of request in the same class with the delegate and I only want to check the response with my function fileexists().

Any hints ?

UPDATE I guess I'll have to do a synchronious request like the following, but I get always 0x0000000000000000 as a response::

   let urlPath: String = sURL;
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?
    >=nil
    var error: NSErrorPointer = nil
    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
    var err: NSError
    println(response)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Swift 3.0 version of Martin R's answer written asynchronously (the main thread isn't blocked):

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

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

    task.resume()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...