将解析后的JSON数据从数据模型传递到View Controller

时间:2017-04-03 22:29:33

标签: ios swift3

好的,我已经坚持了几天。我有一个AuthService类,它通过Id验证和请求帐户,然后使用Account Data类中的静态函数来解析JSON数据。我在我的viewController中调用的AuthService类中有一个委托。当我调用我的委托时,我可以在解析时查看我的数据。我希望能够在我的viewController中使用这个解析的数据。我一直在四处走动,我无法弄清楚访问这些数据。这是我的相关代码......

// AuthService.swift

protocol AuthServiceDelegate: class {
    func loadMe()
 }

class AuthService {
  static let instance = AuthService()
  weak var delegate: AuthServiceDelegate?
  var account = Account()
  var myAccount = [Account]()

let defaults = UserDefaults.standard
var DEFAULTS_ID = UserDefaults.standard.object(forKey: "DEFAULTS_ID")
var _id: String?

  func fetchProfile(for id: String) {
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
    guard let URL = URL(string: "\(GET_ACCOUNT_ID)/\(account.id)") else { return }
    var request = URLRequest(url: URL)
    request.httpMethod = "GET"

    let token = self.authToken
    request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
    request.addValue("Content-Type", forHTTPHeaderField: "application-json")

    do {
        let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
            if (error == nil) {
                // Success
                let statusCode = (response as! HTTPURLResponse).statusCode
                print("URL Session Task for fetching Account By ID Succeeded: HTTP \(statusCode) :Account info loaded" )
                // Parse JSON Data
                if let data = data {
                    self.myAccount = Account.parseAccountJSONData(data: data)
                    self.delegate?.loadMe()
                }
            } else {
                // Failure
                print("URL Session Task Failed: \(error!.localizedDescription)")
            }
        })
        task.resume()
        session.finishTasksAndInvalidate()

    } catch let err {
        print(err)
    }
}

//帐户数据模型 - Account.swift

class Account {

var id: String = ""
var username: String = ""
var name: String = ""
var bio: String = ""
var profileImageURL: String = ""
var website: String = ""
var __v: Int?

static func parseAccountJSONData(data: Data) -> [Account] {

    var myAccount = [Account]()

    do {

        let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        print(jsonResult)

        if let accountData = jsonResult as? [Dictionary<String,AnyObject>] {
            for info in accountData {
                var accountInfo = Account()
                accountInfo.username = info["username"] as! String
                accountInfo.id = info["_id"] as! String
                accountInfo.name = info["name"] as! String
                accountInfo.bio = info["bio"] as! String
                accountInfo.profileImageURL = info["profileImageURL"] as! String
                accountInfo.website = info["website"] as! String
                accountInfo.__v = info["__v"] as! Int
                myAccount.append(accountInfo)

                print("This is your account USER_ID \(accountInfo.id)")

            } // else // { return }
        }
    } catch let err {
        print(err)
    }
    return myAccount
}

// ViewController类

class ProfileVC: UIViewController {

@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var websiteLabel: UILabel!

var authService = AuthService.instance
var defaults = UserDefaults.standard
var logInVC: LogInVC?
var DEFAULTS_ID = UserDefaults.standard.object(forKey: "DEFAULTS_ID")
var currentAccount: Account!

override func viewDidLoad() {
    super.viewDidLoad()

    authService.delegate = self

    authService.fetchProfile(for: DEFAULTS_ID as! String)

    if let account = currentAccount {

        authService.fetchProfile(for: DEFAULTS_ID as! String)

        nameLabel.text = account.name
        bioLabel.text = account.bio
        websiteLabel.text = currentAccount.website
    }
    print(DEFAULTS_ID!)

}

extension ProfileVC: AuthServiceDelegate {
    func loadMe() {
    }
}

这是路由,也是经过身份验证的用户findById enter image description here 以下是我的viewController中通过Account类从AuthService中的委托调用的数据。 enter image description here  我的问题是如何在viewController中访问此数据以更新我的UI?我已经坚持了几天。我可以使用其他dbCollections,因为它们都是通过各自类的ObjectIds在TableViews中加载了已配置的单元格。然而,当我不使用tableview时,我无法使用它,因为我只希望经过身份验证的用户访问他们的个人资料,以便他们可以更新他们的信息。

帮助..我已经通过几种不同的路由和GETS解析了几个数据,但我无法访问这些特定的数据,除非我使用的是collectionView或tableView,我不需要。

0 个答案:

没有答案