如何使用Alamofire和SwiftyJSON从Json保存数据?

时间:2019-06-06 16:09:59

标签: ios json swift alamofire swifty-json

我正在尝试使用这两个库将json(链接:“ https://learnappmaking.com/ex/books.json”)中的“作者”数据保存到名为“作者”的全局变量中。但它仅在func Alamofire.request(url).responseJSON的结尾关闭时有效。当我从尾随的闭包之外的某个位置访问名为“ authors”的全局变量时,得到的是一个空字符串数组。

有人可以解释这种情况的原因吗? 非常感谢。

class ViewController: UIViewController {

    var authors = [String]()
    let url = "https://learnappmaking.com/ex/books.json"


    func getAuthorsCount() {
        print("the number of authors : \(authors.count)") // I hope that here, the number of authors should be 3 too! actually, it is 0. Why? 

        // this for loop doesn't get excuted
        for author in authors {
            print(author)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        Alamofire.request(url).responseJSON { response in
            if let data = response.data {
                if let json = try? JSON(data: data) {
                    for item in json["books"].arrayValue {
                        var outputString: String
                        print(item["author"])
                        outputString = item["author"].stringValue
                        //urlOfProjectAsset.append(outputString)
                        self.authors.append(outputString)
                        print("authors.count: \(self.authors.count)")
                    }
                }
            }
    }

        getAuthorsCount()
        print("-------------")
    }
}

实际输出是:

enter image description here


更新: 我调整了代码:

class ViewController: UIViewController {

    var authors = [String]()
    let url = "https://learnappmaking.com/ex/books.json"


    func getAuthorsCount() {
        print("the number of authors : \(authors.count)")

        // this for loop doesn't get excuted
        for author in authors {
            print(author)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        Alamofire.request(url).responseJSON { response in
            if let data = response.data {
                if let json = try? JSON(data: data) {
                    for item in json["books"].arrayValue {
                        var outputString: String
                        //print(item["author"])
                        outputString = item["author"].stringValue
                        //urlOfProjectAsset.append(outputString)
                        self.authors.append(outputString)
                        //print("authors.count: \(self.authors.count)")
                    }
                self.getAuthorsCount() // I added this line of code.
                }
            }
    }
        getAuthorsCount()
        print("-------------")
    }
}

但是为什么func getAuthorsCount()(不是自版本)仍打印空字符串数组?我认为结果应该与 func self.getAuthorsCount()已打印。 我现在很困惑 再一次,我想使用保存在名为“ authors”的变量中的数据,但是我只有一个空字符串数组。

2 个答案:

答案 0 :(得分:0)

我将尽力回答您的所有问题:

  • 数据是持久性的

  • 您正在执行以下操作:Alamo.request(网络调用)-> getAuthors(打印结果-空)-> 响应(接收响应)-> self.authors.append(保存响应)-> self.authors(打印结果)

  • 您需要执行的操作:Alamo.request(网络通话)->响应(接收响应)-> self.authors.append(保存响应)-> self.getAuthors或getAuthors(相同)(在响应内部) {})

一旦获得结果,就需要在响应回调中调用getAuthors:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        Alamofire.request(url).responseJSON { response in
            if let data = response.data {
                if let json = try? JSON(data: data) {
                    for item in json["books"].arrayValue {
                        var outputString: String
                        print(item["author"])
                        outputString = item["author"].stringValue
                        //urlOfProjectAsset.append(outputString)
                        self.authors.append(outputString)
                        print("authors.count: \(self.authors.count)")
                    }

                    self.getAuthorsCount()
                    print("-------------")
                   //Do whatever you want from here : present/push 


                }
            }
        }

然后您可以使用保存的数据:

  • 要将数据发送到另一个ViewController,可以使用各种方法(present / push,closure / callback等)
  • 通常,您将有一个加载微调器来等待网络 回答,然后您将显示您的下一个控制器

答案 1 :(得分:0)

通过直接消息请求:仅Swift方式。只需将其粘贴到空白的Playground中即可:

import Foundation

final class NetworkService {

  enum ServiceError: LocalizedError {
    case invalidUrl
    case networkingError(error: Error)
    case parsingError

    var localizedDescription: String? { return String(describing: self) }
  }


  func request(completion: @escaping (Result<[UserObject], Error>) -> Void ) {

    guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else {
      completion(.failure(ServiceError.invalidUrl))
      return
    }

    let dataTask = URLSession.shared.dataTask(with: url) { (jsonData, response, error) in
      if let jsonData = jsonData {
        let jsonDecoder = JSONDecoder()

        do {
          let users = try jsonDecoder.decode([UserObject].self, from: jsonData)
          completion(.success(users))
        } catch {
          completion(.failure(ServiceError.parsingError))
        }

      } else if let error = error {
        completion(.failure(ServiceError.networkingError(error: error)))
      }
    }
    dataTask.resume()

  }
}

struct UserObject: Codable {
  let id: Int
  let name: String
  let username: String
  let email: String?
  let website: String?
}


let networkService = NetworkService()
networkService.request { result in

  switch result {
  case .success(let users):
    debugPrint("Received \(users.count) users from REST API")
    debugPrint(users)
  case .failure(let error):
    debugPrint(error.localizedDescription)
  }

}