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

时间:2017-11-03 13:46:52

标签: ios swift uitableview uiactivityindicatorview dispatch-async

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

我已经让这个类让请求变得更容易了,但是当涉及到线程和那种东西时我感到困惑......

基本上,我有一个简单的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()
    }
}

1 个答案:

答案 0 :(得分:0)

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


以下是您的示例,以及如何管理它。

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