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


93

我已经在我的Swift项目中创建了一个实用程序类,用于处理所有REST请求和响应。我建立了一个简单的REST API,因此可以测试我的代码。我创建了一个需要返回NSArray的类方法,但是由于API调用是异步的,因此我需要从异步调用内的方法中返回。问题是异步返回void。如果我在Node上执行此操作,则将使用JS promises,但我找不到能在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...
    }
}

5
这个错误在Stack Overflow上非常常见,以至于我写了一系列博客文章来解决这个问题,首先是programmingios.net/what-asynchronous-means
matt

Answers:


96

您可以传递回调,并在异步调用中调用回调

就像是:

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

感谢那。我的最后一个问题是如何从视图控制器调用此类方法。当前代码如下: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) }
Mark Tyers 2014年

13

Swiftz已经提供了Future,这是Promise的基本组成部分。未来是一个不能失败的承诺(此处所有术语均基于Scala的解释,其中Promise是Monad)。

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

希望最终会扩展到完整的Scala风格的Promise(我可能会自己写;我相信其他PR也会受到欢迎; Future已经存在并不困难)。

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

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

笔记

  • 我不建议给函数加上前缀 get在Swift中。它将破坏与ObjC的某些互操作性。
  • 我建议先解析到一个Book对象,然后再将结果返回为Future。该系统有几种可能会发生故障的方法,如果在将所有这些事情包装成一个之前检查所有这些事情,它会更加方便Future。前往[Book]是更好为您的银行代码比周围的移交休息NSArray

4
Swiftz不再支持Future。但是看看github.com/mxcl/PromiseKit,它与Swiftz一起使用非常好!
badeleux

我花了几秒钟才意识到您没有写Swift,而是写了Swift z
Honey,

4
听起来“ Swiftz”是Swift的第三方功能库。由于您的答案似乎基于该库,因此应明确声明。(例如:“有一个名为'Swiftz'的第三方库,它支持诸如Futures之类的功能结构,如果您想实现Promises,它应该作为一个很好的起点。”否则,您的读者只会想知道为什么您拼错了拼写”迅速”。
Duncan C


1
@Rob get前缀表示ObjC中的按引用返回(例如in中-[UIColor getRed:green:blue:alpha:])。当我写这篇文章时,我担心进口商会利用这一事实(例如自动返回一个元组)。事实证明他们还没有。当我写这篇文章的时候,我可能也忘记了KVC支持访问者的“ get”前缀(这是我学到的,并且忘记了很多次)。因此同意;我还没有遇到领导get打破任何情况的情况。这只会误导那些了解ObjC“获取”含义的人。
罗布·纳皮尔

9

基本模式是使用完成处理程序闭包。

例如,在即将推出的Swift 5中,您将使用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 .success(let genres):
        // use genres here, e.g. update model and UI

    case .failure(let error):
        print(error.localizedDescription)
    }
}

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

注意,上面我将完成处理程序分派回主队列,以简化模型和UI更新。一些开发人员对此做法表示例外,URLSession他们要么使用所使用的任何队列,要么使用自己的队列(要求调用者自己手动同步结果)。

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


较早的Swift 4模式是:

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

        // parse response here

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

你会这样称呼它:

fetchGenres { genres, error in
    guard let genres = genres, error == nil else {
        // handle failure to get valid response here

        return
    }

    // use genres here
}

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

请注意,以上我已经停止使用NSArray(我们不再使用那些桥接的Objective-C类型)。我假设我们有一个Genre类型,并且大概使用JSONDecoder而不是对其JSONSerialization进行解码。但是此问题没有足够的有关底层JSON的信息以在此处进行详细介绍,因此我为避免混淆核心问题(将闭包用作完成处理程序)而将其省略。


您也可以Result在Swift 4及更低版本中使用它,但是您必须自己声明枚举。我多年来一直在使用这种模式。
vadian

是的,当然,我也是如此。但是,看起来它只是被Apple随Swift 5的发布而接受了。他们来晚了。
罗布

7

迅捷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
}

2

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

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

2

我希望您仍然不会陷入困境,但是简短的答案是您不能在Swift中做到这一点。

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


1
他也可以迅速作出承诺。但是callbackclosure正如您指出的那样,苹果目前推荐的aproceh是与s一起使用,或者delegation像较旧的可可API一样使用
Mojtaba Hosseini

您对诺言正确。但是Swift没有为此提供本机API,因此他必须使用PromiseKit或其他替代方法。
LironXYZ

1

创建回调函数的方式有3种,分别是:1.完成处理程序2.通知3.委托

完成处理程序 内部的一组代码块在源可用时执行并返回,处理程序将等到响应到来之后才可以更新UI。

通知 信息束在所有应用程序上被触发,Listner可以检索n个信息。通过项目获取信息的异步​​方式。

委托 调用委托时将触发一组方法,必须通过方法本身提供源


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

-1

快速实现回调的方法主要有3种

  1. 封闭/完成处理程序

  2. 代表们

  3. 通知事项

一旦异步任务完成,也可以使用观察者来获得通知。


-2

每个优秀的API管理器都希望满足一些非常通用的要求:将实现面向协议的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)
        }
    }

}

-2

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

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)")
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.