在安全加载 API 数据时显示 UIActivityIndi​​cator

Display UIActivityIndicator while loading API data safely

我正在开发这个应用程序,并且已经为它开发了一个完整的 API。但是,现在我已经来到前端部分(IOS 应用程序),我不确定如何以正确的方式加载该数据。

我做这个 class 是为了让请求更容易一些,但是当涉及到线程和诸如此类的东西时,我感到困惑...

基本上,我有一个简单的 UITableView 设置,我希望它显示我从 API 中获取的数据。在获取过程中,我需要它显示一个 UIActivityIndicator,它也必须自动隐藏。

我到底该怎么做? (特别是自动的UIActivityIndicator

这是我的请求结构:

//
//  Request.swift
//  Voots
//
//  Created by Carlo on 16/10/2017.
//  Copyright © 2017 Carlo. All rights reserved.
//

import Foundation

struct Request {

    // Post request with specific url, parameters and token
    func post(params: [String: String], url: String, token: String?, 
        completion: ((Data, URLResponse) -> ())?) {


        let nsUrl = NSURL(string: url)
        var request = URLRequest(url: nsUrl! as URL)

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        // If a token was provided, add it.
        if token != nil {
            request.addValue("Bearer \(String(describing: token!))", forHTTPHeaderField: "Authorization")
            print(request.value(forHTTPHeaderField: "Authorization")!)

        }

        request.httpMethod = "POST"

        guard let httpBody = try? JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) else {
            return
        }

        request.httpBody = httpBody

        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in

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

        }.resume()

    }

    func get(url: String, token: String?, completion: ((Data, URLResponse) -> ())?) {
        let nsUrl = NSURL(string: url)
        var request = URLRequest(url: nsUrl! as URL)

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        // If a token was provided, add it.
        if token != nil {
            request.addValue("Bearer \(String(describing: token!))", forHTTPHeaderField: "Authorization")
            print(request.value(forHTTPHeaderField: "Authorization")!)

        }

        request.httpMethod = "GET"

        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in

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

            }.resume()
    }
}

这里是现成(可用)库的列表,如果您不想添加手动操作来管理它:


这是给您的示例,您可以如何管理它。

class ViewController: UIViewController {

    // Create an IBOutlet of indicator or you can create it programatically also.
    @IBOutlet weak var activitIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        activitIndicator.isHidden = false
        Request.post(params: <#T##[String : String]#>, url: <#T##String#>, token: <#T##String?#>) { (<#Data#>, <#URLResponse#>) in
            DispatchQueue.main.async(execute: {
                self.activitIndicator.isHidden = true
            })
        }

    }
}


struct Request {

    // Post request with specific url, parameters and token
    // Note: use static function
    static func post(params: [String: String], url: String, token: String?,
              completion: ((Data, URLResponse) -> ())?) {


        let nsUrl = NSURL(string: url)
        var request = URLRequest(url: nsUrl! as URL)

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        // If a token was provided, add it.
        if token != nil {
            request.addValue("Bearer \(String(describing: token!))", forHTTPHeaderField: "Authorization")
            print(request.value(forHTTPHeaderField: "Authorization")!)

        }

        request.httpMethod = "POST"

        guard let httpBody = try? JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) else {
            return
        }

        request.httpBody = httpBody

        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in

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

            }.resume()

    }

    // Note: use static function
    static func get(url: String, token: String?, completion: ((Data, URLResponse) -> ())?) {
        let nsUrl = NSURL(string: url)
        var request = URLRequest(url: nsUrl! as URL)

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        // If a token was provided, add it.
        if token != nil {
            request.addValue("Bearer \(String(describing: token!))", forHTTPHeaderField: "Authorization")
            print(request.value(forHTTPHeaderField: "Authorization")!)

        }

        request.httpMethod = "GET"

        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in

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

            }.resume()
    }
}