从 Swift 函数中的异步调用返回数据

Returning data from async call in Swift function

提问人:Mark Tyers 提问时间:8/8/2014 更新时间:8/25/2023 访问量:87772

问:

我在我的 Swift 项目中创建了一个实用程序类,用于处理所有 REST 请求和响应。我构建了一个简单的 REST API,因此我可以测试我的代码。我创建了一个需要返回 NSArray 的类方法,但由于 API 调用是异步的,我需要从异步调用中的方法返回。问题是异步返回 void。 如果我在 Node 中执行此操作,我会使用 JS promise,但我无法找到在 Swift 中有效的解决方案。

import Foundation

class Bookshop {
    class func getGenres() -> NSArray {
        println("Hello inside getGenres")
        let urlPath = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list"
        println(urlPath)
        let url: NSURL = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        var resultsArray:NSArray!
        let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
            println("Task completed")
            if(error) {
                println(error.localizedDescription)
            }
            var err: NSError?
            var options:NSJSONReadingOptions = NSJSONReadingOptions.MutableContainers
            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: options, error: &err) as NSDictionary
            if(err != nil) {
                println("JSON Error \(err!.localizedDescription)")
            }
            //NSLog("jsonResults %@", jsonResult)
            let results: NSArray = jsonResult["genres"] as NSArray
            NSLog("jsonResults %@", results)
            resultsArray = results
            return resultsArray // error [anyObject] is not a subType of 'Void'
        })
        task.resume()
        //return "Hello World!"
        // I want to return the NSArray...
    }
}
iOS REST 异步 Swift

评论


答:

104赞 Alexey Globchastyy 8/8/2014 #1

可以传递回调,在异步调用内调用回调

像这样:

class func getGenres(completionHandler: (genres: NSArray) -> ()) {
    ...
    let task = session.dataTaskWithURL(url) {
        data, response, error in
        ...
        resultsArray = results
        completionHandler(genres: resultsArray)
    }
    ...
    task.resume()
}

然后调用此方法:

override func viewDidLoad() {
    Bookshop.getGenres {
        genres in
        println("View Controller: \(genres)")     
    }
}

评论

0赞 Mark Tyers 8/8/2014
谢谢你。我的最后一个问题是如何从我的视图控制器调用这个类方法。目前代码是这样的:override func viewDidLoad() { super.viewDidLoad() var genres = Bookshop.getGenres() // Missing argument for parameter #1 in call //var genres:NSArray //Bookshop.getGenres(genres) NSLog("View Controller: %@", genres) }
15赞 Rob Napier 8/8/2014 #2

Swiftz 已经提供了 Future,这是 Promise 的基本构建块。未来是一个不会失败的承诺(这里的所有术语都基于 Scala 解释,其中承诺是一个单子)。

https://github.com/maxpow4h/swiftz/blob/master/swiftz/Future.swift

希望最终能扩展到一个完整的 Scala 风格的 Promise(我可能会在某个时候自己写;我相信其他 PR 会受到欢迎;未来已经到位,这并不难)。

在你的特定情况下,我可能会创建一个(基于 Alexandros Salazar 的 Result 版本)。那么你的方法签名将是:Result<[Book]>

class func fetchGenres() -> Future<Result<[Book]>> {

笔记

  • 我不建议在 Swift 中为函数添加前缀。它将破坏与 ObjC 的某些互操作性。get
  • 我建议先解析一个对象,然后再将结果作为 .这个系统有几种方式可能会失败,如果你在将它们包装成一个 .对于其余的 Swift 代码来说,获得 to 比交出一个 .BookFutureFuture[Book]NSArray

评论

4赞 badeleux 7/28/2015
Swiftz 不再支持 .但是看看它 github.com/mxcl/PromiseKit 与 Swiftz 配合得很好!Future
1赞 mfaani 8/19/2017
我花了几秒钟才意识到你没有写 Swift 而是写了 Swiftz
6赞 Duncan C 1/3/2018
听起来“Swiftz”是 Swift 的第三方函数库。由于您的答案似乎基于该库,因此您应该明确说明。(例如,“有一个名为'Swiftz'的第三方库支持像 Futures 这样的函数结构,如果你想实现 Promises,它应该是一个很好的起点。否则,你的读者只会想知道你为什么拼错了“Swift”。
4赞 Ahmad F 3/1/2018
请注意,github.com/maxpow4h/swiftz/blob/master/swiftz/Future.swift 不再工作。
1赞 Rob Napier 2/9/2019
@Rob 前缀表示 ObjC 中的引用回值(例如 )。当我写这篇文章时,我担心导入者会利用这一事实(例如,自动返回元组)。事实证明,他们没有。当我写这篇文章时,我可能也忘记了 KVC 支持访问器的“get”前缀(这是我学到并忘记过几次的东西)。于是同意了;我没有遇到过任何领先破坏事情的情况。它只是误导了那些知道 ObjC “get” 含义的人。get-[UIColor getRed:green:blue:alpha:]get
4赞 Nebojsa Nadj 5/17/2017 #3

Swift 3 版本的 @Alexey Globchastyy 的回答:

class func getGenres(completionHandler: @escaping (genres: NSArray) -> ()) {
...
let task = session.dataTask(with:url) {
    data, response, error in
    ...
    resultsArray = results
    completionHandler(genres: resultsArray)
}
...
task.resume()
}
-1赞 CrazyPro007 5/20/2018 #4
self.urlSession.dataTask(with: request, completionHandler: { (data, response, error) in
            self.endNetworkActivity()

            var responseError: Error? = error
            // handle http response status
            if let httpResponse = response as? HTTPURLResponse {

                if httpResponse.statusCode > 299 , httpResponse.statusCode != 422  {
                    responseError = NSError.errorForHTTPStatus(httpResponse.statusCode)
                }
            }

            var apiResponse: Response
            if let _ = responseError {
                apiResponse = Response(request, response as? HTTPURLResponse, responseError!)
                self.logError(apiResponse.error!, request: request)

                // Handle if access token is invalid
                if let nsError: NSError = responseError as NSError? , nsError.code == 401 {
                    DispatchQueue.main.async {
                        apiResponse = Response(request, response as? HTTPURLResponse, data!)
                        let message = apiResponse.message()
                        // Unautorized access
                        // User logout
                        return
                    }
                }
                else if let nsError: NSError = responseError as NSError? , nsError.code == 503 {
                    DispatchQueue.main.async {
                        apiResponse = Response(request, response as? HTTPURLResponse, data!)
                        let message = apiResponse.message()
                        // Down time
                        // Server is currently down due to some maintenance
                        return
                    }
                }

            } else {
                apiResponse = Response(request, response as? HTTPURLResponse, data!)
                self.logResponse(data!, forRequest: request)
            }

            self.removeRequestedURL(request.url!)

            DispatchQueue.main.async(execute: { () -> Void in
                completionHandler(apiResponse)
            })
        }).resume()
9赞 Jaydeep Vora 6/13/2018 #5

斯威夫特 4.0

对于异步请求-响应,可以使用完成处理程序。见下文,我修改了带有完成句柄范例的解决方案。

func getGenres(_ completion: @escaping (NSArray) -> ()) {

        let urlPath = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list"
        print(urlPath)

        guard let url = URL(string: urlPath) else { return }

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else { return }
            do {
                if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
                    let results = jsonResult["genres"] as! NSArray
                    print(results)
                    completion(results)
                }
            } catch {
                //Catch Error here...
            }
        }
        task.resume()
    }

您可以按如下方式调用此函数:

getGenres { (array) in
    // Do operation with array
}
3赞 LironXYZ 11/16/2018 #6

我希望你仍然被困在这个上,但简短的回答是你不能在 Swift 中做到这一点。

另一种方法是返回一个回调,该回调将在准备就绪后立即提供所需的数据。

评论

1赞 Mojtaba Hosseini 11/16/2018
他也可以迅速做出承诺。但是苹果目前推荐的 aproceh 是与 s 一起使用,正如你指出的那样,或者像旧的 cocoa API 一样使用callbackclosuredelegation
0赞 LironXYZ 11/16/2018
你对承诺的看法是对的。但是 Swift 没有为此提供原生 API,因此他必须使用 PromiseKit 或其他替代方案。
27赞 Rob 2/9/2019 #7

在 Swift 5.5(iOS 15、macOS 12)中引入,我们现在将使用 - 模式:asyncawait

func fetchGenres() async throws -> [Genre] {
    …
    let (data, _) = try await URLSession.shared.dataTask(for: request)
    return try JSONDecoder().decode([Genre].self, from: data)
}

我们这样称呼它:

let genres = try await fetchGenres()

- 语法比下面我原始答案中概述的传统完成处理程序模式要简洁自然得多。asyncawait

有关更多信息,请参阅在 Swift 中满足 async/await


历史模式是使用完成处理程序闭包。

例如,我们经常使用:Result

func fetchGenres(completion: @escaping (Result<[Genre], Error>) -> Void) {
    ...
    URLSession.shared.dataTask(with: request) { data, _, error in 
        if let error = error {
            DispatchQueue.main.async {
                completion(.failure(error))
            }
            return
        }

        // parse response here

        let results = ...
        DispatchQueue.main.async {
            completion(.success(results))
        }
    }.resume()
}

你可以这样称呼它:

fetchGenres { results in
    switch results {
    case .failure(let error):
        print(error.localizedDescription)

    case .success(let genres):
        // use `genres` here, e.g. update model and UI            
    }
}

// but don’t try to use `genres` here, as the above runs asynchronously

请注意,上面我将完成处理程序调度回主队列,以简化模型和 UI 更新。一些开发人员反对这种做法,要么使用任何使用的队列,要么使用自己的队列(要求调用者自己手动同步结果)。URLSession

但这在这里并不重要。关键问题是使用完成处理程序来指定异步请求完成时要运行的代码块。


请注意,上面我停用了(我们不再使用那些桥接的 Objective-C 类型)。我假设我们有一个类型,我们大概使用 ,而不是 来解码它。但是这个问题没有足够的关于底层 JSON 的信息来深入了解这里的细节,所以我省略了这一点,以避免混淆核心问题,即使用闭包作为完成处理程序。NSArrayGenreJSONDecoderJSONSerialization

评论

0赞 vadian 2/14/2019
您也可以在 Swift 4 及更低版本中使用,但您必须自己声明枚举。我多年来一直使用这种模式。Result
0赞 Rob 2/15/2019
是的,当然,我也是。但看起来它只是随着 Swift 5 的发布而被苹果所接受。他们只是来晚了。
-1赞 Shubham Mishra 2/14/2019 #8

在 swift 中实现回调主要有 3 种方式

  1. 闭包/完成处理程序

  2. 代表

  3. 通知

观察者还可用于在异步任务完成后收到通知。

3赞 IRANNA SALUNKE 2/21/2019 #9

有 3 种方法可以创建回调函数,即: 1. 完成处理程序 2. 通知 3. 参会代表

完成处理程序当 source 可用时,在块的内部集合被执行并返回,Handler 将等待响应到来,以便 UI 可以更新。

通知所有应用程序都会触发一堆信息,Listner 可以检索 n 利用该信息。通过项目获取信息的异步方式。

代表调用委托时会触发一组方法,必须通过方法本身提供 Source

-1赞 Rashpinder Maan 4/17/2019 #10

有一些非常通用的要求,希望每个优秀的 API Manager 都能满足: 将实现面向协议的 API 客户端。

APIClient 初始接口

protocol APIClient {
   func send(_ request: APIRequest,
              completion: @escaping (APIResponse?, Error?) -> Void) 
}

protocol APIRequest: Encodable {
    var resourceName: String { get }
}

protocol APIResponse: Decodable {
}

现在请检查完整的 api 结构

// ******* This is API Call Class  *****
public typealias ResultCallback<Value> = (Result<Value, Error>) -> Void

/// Implementation of a generic-based  API client
public class APIClient {
    private let baseEndpointUrl = URL(string: "irl")!
    private let session = URLSession(configuration: .default)

    public init() {

    }

    /// Sends a request to servers, calling the completion method when finished
    public func send<T: APIRequest>(_ request: T, completion: @escaping ResultCallback<DataContainer<T.Response>>) {
        let endpoint = self.endpoint(for: request)

        let task = session.dataTask(with: URLRequest(url: endpoint)) { data, response, error in
            if let data = data {
                do {
                    // Decode the top level response, and look up the decoded response to see
                    // if it's a success or a failure
                    let apiResponse = try JSONDecoder().decode(APIResponse<T.Response>.self, from: data)

                    if let dataContainer = apiResponse.data {
                        completion(.success(dataContainer))
                    } else if let message = apiResponse.message {
                        completion(.failure(APIError.server(message: message)))
                    } else {
                        completion(.failure(APIError.decoding))
                    }
                } catch {
                    completion(.failure(error))
                }
            } else if let error = error {
                completion(.failure(error))
            }
        }
        task.resume()
    }

    /// Encodes a URL based on the given request
    /// Everything needed for a public request to api servers is encoded directly in this URL
    private func endpoint<T: APIRequest>(for request: T) -> URL {
        guard let baseUrl = URL(string: request.resourceName, relativeTo: baseEndpointUrl) else {
            fatalError("Bad resourceName: \(request.resourceName)")
        }

        var components = URLComponents(url: baseUrl, resolvingAgainstBaseURL: true)!

        // Common query items needed for all api requests
        let timestamp = "\(Date().timeIntervalSince1970)"
        let hash = "\(timestamp)"
        let commonQueryItems = [
            URLQueryItem(name: "ts", value: timestamp),
            URLQueryItem(name: "hash", value: hash),
            URLQueryItem(name: "apikey", value: "")
        ]

        // Custom query items needed for this specific request
        let customQueryItems: [URLQueryItem]

        do {
            customQueryItems = try URLQueryItemEncoder.encode(request)
        } catch {
            fatalError("Wrong parameters: \(error)")
        }

        components.queryItems = commonQueryItems + customQueryItems

        // Construct the final URL with all the previous data
        return components.url!
    }
}

// ******  API Request Encodable Protocol *****
public protocol APIRequest: Encodable {
    /// Response (will be wrapped with a DataContainer)
    associatedtype Response: Decodable

    /// Endpoint for this request (the last part of the URL)
    var resourceName: String { get }
}

// ****** This Results type  Data Container Struct ******
public struct DataContainer<Results: Decodable>: Decodable {
    public let offset: Int
    public let limit: Int
    public let total: Int
    public let count: Int
    public let results: Results
}
// ***** API Errro Enum ****
public enum APIError: Error {
    case encoding
    case decoding
    case server(message: String)
}


// ****** API Response Struct ******
public struct APIResponse<Response: Decodable>: Decodable {
    /// Whether it was ok or not
    public let status: String?
    /// Message that usually gives more information about some error
    public let message: String?
    /// Requested data
    public let data: DataContainer<Response>?
}

// ***** URL Query Encoder OR JSON Encoder *****
enum URLQueryItemEncoder {
    static func encode<T: Encodable>(_ encodable: T) throws -> [URLQueryItem] {
        let parametersData = try JSONEncoder().encode(encodable)
        let parameters = try JSONDecoder().decode([String: HTTPParam].self, from: parametersData)
        return parameters.map { URLQueryItem(name: $0, value: $1.description) }
    }
}

// ****** HTTP Pamater Conversion Enum *****
enum HTTPParam: CustomStringConvertible, Decodable {
    case string(String)
    case bool(Bool)
    case int(Int)
    case double(Double)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()

        if let string = try? container.decode(String.self) {
            self = .string(string)
        } else if let bool = try? container.decode(Bool.self) {
            self = .bool(bool)
        } else if let int = try? container.decode(Int.self) {
            self = .int(int)
        } else if let double = try? container.decode(Double.self) {
            self = .double(double)
        } else {
            throw APIError.decoding
        }
    }

    var description: String {
        switch self {
        case .string(let string):
            return string
        case .bool(let bool):
            return String(describing: bool)
        case .int(let int):
            return String(describing: int)
        case .double(let double):
            return String(describing: double)
        }
    }
}

/// **** This is your API Request Endpoint  Method in Struct *****
public struct GetCharacters: APIRequest {
    public typealias Response = [MyCharacter]

    public var resourceName: String {
        return "characters"
    }

    // Parameters
    public let name: String?
    public let nameStartsWith: String?
    public let limit: Int?
    public let offset: Int?

    // Note that nil parameters will not be used
    public init(name: String? = nil,
                nameStartsWith: String? = nil,
                limit: Int? = nil,
                offset: Int? = nil) {
        self.name = name
        self.nameStartsWith = nameStartsWith
        self.limit = limit
        self.offset = offset
    }
}

// *** This is Model for Above Api endpoint method ****
public struct MyCharacter: Decodable {
    public let id: Int
    public let name: String?
    public let description: String?
}


// ***** These below line you used to call any api call in your controller or view model ****
func viewDidLoad() {
    let apiClient = APIClient()

    // A simple request with no parameters
    apiClient.send(GetCharacters()) { response in

        response.map { dataContainer in
            print(dataContainer.results)
        }
    }

}
-1赞 a.palo 4/24/2019 #11

这是一个可能会有所帮助的小用例:-

func testUrlSession(urlStr:String, completionHandler: @escaping ((String) -> Void)) {
        let url = URL(string: urlStr)!


        let task = URLSession.shared.dataTask(with: url){(data, response, error) in
            guard let data = data else { return }
            if let strContent = String(data: data, encoding: .utf8) {
            completionHandler(strContent)
            }
        }


        task.resume()
    }

调用函数时:-

testUrlSession(urlStr: "YOUR-URL") { (value) in
            print("Your string value ::- \(value)")
}
2赞 Johnykutty 4/30/2021 #12

斯威夫特 5.5:

TL;DR:Swift 5.5 尚未发布(在撰写本文时)。要使用 swift 5.5,请从此处下载 swift 工具链开发快照并添加编译器标志。在这里阅读更多内容-Xfrontend -enable-experimental-concurrency

这可以通过功能轻松实现。async/await

为此,您应该将函数标记为然后在块内执行操作,如下所示。asyncwithUnsafeThrowingContinuation

class Bookshop {
  class func getGenres() async throws -> NSArray {
    print("Hello inside getGenres")
    let urlPath = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list"
    print(urlPath)
    let url = URL(string: urlPath)!
    let session = URLSession.shared
    return try await withUnsafeThrowingContinuation { continuation in
      let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
        print("Task completed")
        if(error != nil) {
          print(error!.localizedDescription)
          continuation.resume(throwing: error!)
          return
        }
        do {
          let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
          let results: NSArray = jsonResult!["genres"] as! NSArray
          continuation.resume(returning: results)
        } catch {
          continuation.resume(throwing: error)
        }
      })
      task.resume()
    }
  }
}

你可以像这样调用这个函数

@asyncHandler
func check() {
  do {
    let genres = try await Bookshop.getGenres()
    print("Result: \(genres)")
  } catch {
    print("Error: \(error)")
  }
}

请记住,在调用方法时,调用方方法应标记为 或Bookshop.getGenresasync@asyncHandler

4赞 drewster 6/11/2021 #13

Swift 5.5,基于异步/等待的解决方案

原始海报提供的原始测试 URL 不再起作用,所以我不得不稍微改变一下。这个解决方案基于我发现的笑话 API。该 API 返回一个笑话,但我将其作为 String () 数组返回,以使其尽可能与原始帖子保持一致。[String]


class Bookshop {
    class func getGenres() async -> [String] {
        print("Hello inside getGenres")
        let urlPath = "https://geek-jokes.sameerkumar.website/api?format=json"
        print(urlPath)
        let url = URL(string: urlPath)!
        let session = URLSession.shared
        
        typealias Continuation = CheckedContinuation<[String], Never>
        let genres = await withCheckedContinuation { (continuation: Continuation) in
            let task = session.dataTask(with: url) { data, response, error in
                print("Task completed")
                
                var result: [String] = []
                defer {
                    continuation.resume(returning: result)
                }
                
                if let error = error {
                    print(error.localizedDescription)
                    return
                }
                guard let data = data else { 
                    return
                }
                
                do {
                    let jsonResult = try JSONSerialization.jsonObject(with: data, options: [.mutableContainers])
                    print("jsonResult is \(jsonResult)")
                    if let joke = (jsonResult as? [String: String])?["joke"] {
                        result = [joke]
                    }
                } catch {
                    print("JSON Error \(error.localizedDescription)")
                    print("data was \(String(describing: String(data: data, encoding: .utf8)))")
                    return
                }
            }
            task.resume()
        }
        
        return genres
    }
}

async {
    let final = await Bookshop.getGenres()
    print("Final is \(final)")
}

这就是你如何使 Swift 函数在单独的任务/线程中实际运行。withCheckedContinuationasync

评论

0赞 Greg 8/25/2023
我有一篇关于一个非常相似问题的帖子,它被烦人地关闭了并引用了这篇文章。这里有很多很棒的东西,但不幸的是,这对我没有任何帮助。stackoverflow.com/questions/76958124/......这就是帖子,我正在尝试进入一个谷歌位置数组,运行获取坐标的函数,然后将其放入 compactMap 的结构中。我试图遵循这里的所有例子,但我无法让它工作。我知道我在这里错过了什么