内容的栏目 * @param int $category 0列表 1频道 2单页 3外链 * @return array */ function category_list($forumlist, $model = 0, $display = 0, $category = 0) { if (empty($forumlist)) return NULL; static $cache = array(); $key = $model . '-' . $display . '-' . $category; if (isset($cache[$key])) return $cache[$key]; if ($display) { foreach ($forumlist as $k => $val) { if (1 == $val['display'] && 1 == $val['type'] && $val['category'] == $category) { $cache[$key][$k] = $val; } } } else { foreach ($forumlist as $k => $val) { if (1 == $val['type'] && $val['category'] == $category) { $cache[$key][$k] = $val; } } } return empty($cache[$key]) ? NULL : $cache[$key]; } /** * @param $forumlist 所有版块列表 不分模型 * @param int $display 0全部CMS栏目 1在首页和频道显示内容的栏目 * @param int $category 0列表 1频道 2单页 3外链 * @return array */ function category_list_show($forumlist, $display = 0, $category = 0) { if (empty($forumlist)) return NULL; static $cache = array(); $key = $display . '-' . $category; if (isset($cache[$key])) return $cache[$key]; if ($display) { foreach ($forumlist as $k => $val) { if (1 == $val['display'] && 1 == $val['type'] && $val['category'] == $category) { $cache[$key][$k] = $val; } } } else { foreach ($forumlist as $k => $val) { if (1 == $val['type'] && $val['category'] == $category) { $cache[$key][$k] = $val; } } } return empty($cache[$key]) ? NULL : $cache[$key]; } /** * @param $forumlist 所有版块列表 * @return mixed BBS栏目数据(仅列表) 尚未开放bbs频道功能 */ function forum_list($forumlist) { if (empty($forumlist)) return array(); static $cache = array(); if (isset($cache['bbs_forum_list'])) return $cache['bbs_forum_list']; $cache['bbs_forum_list'] = array(); foreach ($forumlist as $_fid => $_forum) { if ($_forum['type']) continue; $cache['bbs_forum_list'][$_fid] = $_forum; } return $cache['bbs_forum_list']; } // 导航显示的版块 function nav_list($forumlist) { if (empty($forumlist)) return NULL; static $cache = array(); if (isset($cache['nav_list'])) return $cache['nav_list']; foreach ($forumlist as $fid => $forum) { if (0 == $forum['nav_display']) { unset($forumlist[$fid]); } } return $cache['nav_list'] = $forumlist; } ?>swift - What is the easiest way to reuse the same function to call multiple API endpoints? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - What is the easiest way to reuse the same function to call multiple API endpoints? - Stack Overflow

programmeradmin0浏览0评论

I have a very simple iOS SwiftUI app that has API calls to 7 endpoints. I've written a function to do the API call and decode the data response. In order to reuse the function I will need to replace the endpoint URL string and the class that the data gets decoded to. Passing the endpoint URL string is simple enough, but I don't know how to pass different data classes for each endpoint to the API function.

I have searched high and low for an example, but have found none for my use case. I considered using an enum, but I'm not sure how to implement that either.

Below is the code for my API call function, with the code to pass the URL string, and the data class.

func apiLoader(urlString: String) {
    
    // Create API URL
    //let url = URL(string: ";)
    let url = URL(string: urlString)
    guard let requestUrl = url else { fatalError() }
    
    // Create URL Request
    var request = URLRequest(url: requestUrl)
    
    // Specify Headers to use
    let headers = [
        "x-rapidapi-key": "REDACTED",
        "x-rapidapi-host": "REDACTED.p.rapidapi"
    ]
    
    // Specify HTTP Method to use
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers
    
    // Send HTTP Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        
        // Check if Error took place
        if let error = error {
            print("Error took place \(error)")
            return
        }
        
        // Convert HTTP Response Data to a simple String
        if let data = data.self {
            do {
                
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"
                
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                decoder.dateDecodingStrategy = .formatted(dateFormatter)
                
                let hockeyTimeZones = try decoder.decode(HockeyTimeZones.self, from: data)
                hockeyTimeZones.response!.forEach { timezone in print(timezone) }

                //return hockeyTimeZones

                
            } catch {
                print("Failed to load: \(error)")
                //return Void()
            }
            
        }
    }
    
    task.resume()

    //return HockeyTimeZones()
@Observable class HockeyTimeZones: ObservableObject, Codable {

  var get        : String?   = nil
  var parameters : [String]? = []
  var errors     : [String]? = []
  var results    : Int?      = nil
  var response   : [String]? = []

  enum CodingKeys: String, CodingKey {

    case _get        = "get"
    case _parameters = "parameters"
    case _errors     = "errors"
    case _results    = "results"
    case _response   = "response"
  
  }

    required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)

    get        = try values.decodeIfPresent(String.self   , forKey: ._get        )
    parameters = try values.decodeIfPresent([String].self , forKey: ._parameters )
    errors     = try values.decodeIfPresent([String].self , forKey: ._errors     )
    results    = try values.decodeIfPresent(Int.self      , forKey: ._results    )
    response   = try values.decodeIfPresent([String].self , forKey: ._response   )
 
  }

  init() {

  }
}

I have a very simple iOS SwiftUI app that has API calls to 7 endpoints. I've written a function to do the API call and decode the data response. In order to reuse the function I will need to replace the endpoint URL string and the class that the data gets decoded to. Passing the endpoint URL string is simple enough, but I don't know how to pass different data classes for each endpoint to the API function.

I have searched high and low for an example, but have found none for my use case. I considered using an enum, but I'm not sure how to implement that either.

Below is the code for my API call function, with the code to pass the URL string, and the data class.

func apiLoader(urlString: String) {
    
    // Create API URL
    //let url = URL(string: "https://api-hockey.p.rapidapi/timezone")
    let url = URL(string: urlString)
    guard let requestUrl = url else { fatalError() }
    
    // Create URL Request
    var request = URLRequest(url: requestUrl)
    
    // Specify Headers to use
    let headers = [
        "x-rapidapi-key": "REDACTED",
        "x-rapidapi-host": "REDACTED.p.rapidapi"
    ]
    
    // Specify HTTP Method to use
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers
    
    // Send HTTP Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        
        // Check if Error took place
        if let error = error {
            print("Error took place \(error)")
            return
        }
        
        // Convert HTTP Response Data to a simple String
        if let data = data.self {
            do {
                
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"
                
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                decoder.dateDecodingStrategy = .formatted(dateFormatter)
                
                let hockeyTimeZones = try decoder.decode(HockeyTimeZones.self, from: data)
                hockeyTimeZones.response!.forEach { timezone in print(timezone) }

                //return hockeyTimeZones

                
            } catch {
                print("Failed to load: \(error)")
                //return Void()
            }
            
        }
    }
    
    task.resume()

    //return HockeyTimeZones()
@Observable class HockeyTimeZones: ObservableObject, Codable {

  var get        : String?   = nil
  var parameters : [String]? = []
  var errors     : [String]? = []
  var results    : Int?      = nil
  var response   : [String]? = []

  enum CodingKeys: String, CodingKey {

    case _get        = "get"
    case _parameters = "parameters"
    case _errors     = "errors"
    case _results    = "results"
    case _response   = "response"
  
  }

    required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)

    get        = try values.decodeIfPresent(String.self   , forKey: ._get        )
    parameters = try values.decodeIfPresent([String].self , forKey: ._parameters )
    errors     = try values.decodeIfPresent([String].self , forKey: ._errors     )
    results    = try values.decodeIfPresent(Int.self      , forKey: ._results    )
    response   = try values.decodeIfPresent([String].self , forKey: ._response   )
 
  }

  init() {

  }
}
Share Improve this question edited Feb 2 at 5:11 HangarRash 15k5 gold badges19 silver badges55 bronze badges asked Feb 2 at 5:07 Scott CarperScott Carper 32 silver badges2 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

When you have multiple API calls that return different types of responses that you want to decode, use Swift generics

For example:

 func getData<T: Decodable>(from urlString: String) async -> T? {
     guard let url = URL(string: urlString) else {
         print(URLError(.badURL))
         return nil // <-- todo, deal with errors
     }
     do {
         let (data, response) = try await URLSession.shared.data(from: url)
         guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
             print(URLError(.badServerResponse))
             return nil // <-- todo, deal with errors
         }
         return try JSONDecoder().decode(T.self, from: data) // <--- here
     }
     catch {
          print(error)
         return nil // <-- todo, deal with errors
     }
 }
 

Call it like this:

 .task {
      let theResponse: ApiResponse? = await getData(from: "https://...")
 }

Note the important type ApiResponse? in let theResponse: ApiResponse? = ...., this tells the type getData(...) should use for decoding and to return.

Specific example code:

struct ContentView: View {
    @State private var timeZones: TzResponse?
    
    var body: some View {
        List(timeZones?.response ?? [], id: \.self) { tz in
            Text(tz)
        }
        .task {
            timeZones = await getData(from: "https://api-hockey.p.rapidapi/timezone")
        }
    }

    func getData<T: Decodable>(from urlString: String) async -> T? {
        let apikey = "YOUR-API-KEY-HERE"
        
        guard let url = URL(string: urlString) else {
            print(URLError(.badURL))
            return nil // <-- todo, deal with errors
        }
        
        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("\(apikey)", forHTTPHeaderField: "X-RapidAPI-Key")
        request.addValue("api-hockey.p.rapidapi", forHTTPHeaderField: "X-RapidAPI-Host")
        
        do {
            let (data, response) = try await URLSession.shared.data(for: request)
            //print(String(data: data, encoding: .utf8) as AnyObject)
            let decodedData = try JSONDecoder().decode(T.self, from: data)
            print("\n---< decodedData: \(decodedData)")
            return decodedData
        } catch {
            print(error)
            return nil // <-- todo, deal with errors
        }
    }
}

struct TzResponse: Codable {
    let errors: [String]
    let parameters: [String]
    let response: [String]
    let get: String
    let results: Int
}
发布评论

评论列表(0)

  1. 暂无评论