swift 函数与dataTask返回一个值[重复]

vlju58qv  于 2023-09-30  发布在  Swift
关注(0)|答案(5)|浏览(116)

此问题已在此处有答案

Returning data from async call in Swift function(13个回答)
10天前关闭。
我不想检查我的url statusCode是否等于200,我创建了一个函数,如果statusCode等于200,则返回布尔值,我使用的是dataTask,但我不知道如何返回值:

class func checkUrl(urlString: String) -> Bool{

    let urlPath: String = urlString
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(url: url as URL)
    var response: URLResponse?

    let session = Foundation.URLSession.shared

    var task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let data = data{
            print("data =\(data)")
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")

            if httpResponse.statusCode == 200{
                return true
            } else {
                return false
            }
        }
    })
    task.resume()
}

if else中的返回返回错误:
void函数中出现意外的非void返回值

iswrvxsc

iswrvxsc1#

为了返回值,你应该使用块。试着像这样声明你的函数:

class func checkUrl(urlString: String, finished: ((isSuccess: Bool)->Void) {

    let urlPath: String = urlString
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(url: url as URL)
    var response: URLResponse?

    let session = Foundation.URLSession.shared

    var task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let data = data{
            print("data =\(data)")
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")

            if httpResponse.statusCode == 200{
                finished(isSuccess: true)                
            } else {
                finished(isSuccess: false) 
            }
        }
    })
    task.resume()
}

然后像这样调用它:

checkUrl("http://myBestURL.com", finished { isSuccess in
// Handle logic after return here
})

希望这会有所帮助。

0kjbasz6

0kjbasz62#

如果你想保持原始的返回模式,可以考虑semaphore

func checkUrl(urlString: String) -> Bool {
    if let url = URL(string: fileUrl) {
        var result: Bool!

        let semaphore = DispatchSemaphore(value: 0)  //1. create a counting semaphore

        let session = URLSession.shared
        session.dataTask(with: url, completionHandler: { (data, response, error) in
            result = true  //or false in case
            semaphore.signal()  //3. count it up
        }).resume()

        semaphore.wait()  //2. wait for finished counting

        return result
    }

    return false
}
oo7oh9g9

oo7oh9g93#

Swift4,work in my case尝试在dataTask中添加guard let data = data else { return },如下所示:

URLSession.shared.dataTask(with: request) { (data, response, error) in
    guard let data = data else { return }
    print("get some data")
}.resume()
m3eecexj

m3eecexj4#

您从Void函数返回的值是dataTask(_:, _:)completionHandler闭包
关于你的代码,有一些错误:你不能返回那个值,因为它是在不同的线程上执行的,这是一个异步操作。请看一下这个帖子:Returning data from async call in Swift function

3phpmpom

3phpmpom5#

我也在学习Swift,这是我如何做到这一点的。
在Swift中,可以使用URLSessionDataTask来执行网络请求并异步检索数据。要从数据任务返回数据,通常使用完成处理程序。下面是一个如何执行此操作的示例:

import Foundation

func fetchDataFromURL(_ url: URL, completion: @escaping (Data?, Error?) -> Void) {
    let session = URLSession.shared
    let task = session.dataTask(with: url) { (data, response, error) in
        if let error = error {
            completion(nil, error)
            return
        }

        if let data = data {
            completion(data, nil)
        }
    }

    task.resume()
}

// Example usage
if let url = URL(string: "https://example.com/api/data") {
    fetchDataFromURL(url) { (data, error) in
        if let error = error {
            print("Error: \(error)")
        } else if let data = data {
            // Handle the retrieved data here
            print("Received data: \(data)")
        }
    }
}

相关问题