2017-06-23 73 views
1

我目前正在發送我的json數據到Dictionary在相同的ViewController。我想將它發送到一個名爲Users的類。數據正在顯示在TableView上。發送json數據到單獨的類和顯示在tableView

import UIKit 

class Users: NSObject { 

    var name: String? 
} 



class FriendsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
    var userList = [Users]() 

@IBOutlet weak var myTableView: UITableView! 


final let urlString = "https://api.lookfwd.io/v1/test/users" 

var namesArray = [String]() 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return namesArray.count 

} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell 

    myCell.nameLabel.text = namesArray[indexPath.row] 
    return myCell 
} 


override func viewDidLoad() { 
    super.viewDidLoad() 
    self.downloadJsonWithTask() 


    // Do any additional setup after loading the view. 
} 

func downloadJsonWithTask() { 

    let url = NSURL(string: urlString) 

    var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20) 

    downloadTask.httpMethod = "GET" 

    URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in 

     let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) 

     if let dataArray = (jsonData! as AnyObject).value(forKey: "users") as? NSArray { 
      for data in dataArray{ 


     //   let user = Users() 

     //   user.setValuesForKeys(data as! [String : Any]) 

     //  self.userList.append(user) 


      if let dataDict = data as? NSDictionary { 
        if let title = dataDict.value(forKey: "name") { 
         self.namesArray.append(title as! String) 
        } 
       } 
      print(jsonData!) 
      } 
     } 
     OperationQueue.main.addOperation({ 
      self.myTableView.reloadData() 
     }) 

     print(jsonData!) 

    }).resume() 
} 

} 
+0

之前添加用戶到用戶列表,您需要將您的JSON轉換爲用戶模型。 – Bala

+0

你的問題不清楚。你是否試圖在一個viewcontroller中執行API調用,並想在另一個控制器中顯示數據? – Praveenkumar

+0

不,我想發送數據到我的用戶類,然後在我的桌面視圖中的FriendsViewController顯示名稱 – user8000557

回答

0

您可以修改downloadJSONTask部分只需更換您的downloadJsonWithTask方法

func downloadJsonWithTask() { 

    let url = NSURL(string: urlString) 

    var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20) 

    downloadTask.httpMethod = "GET" 

    URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in 

     if let response = data { 
      if let jsonData = try? JSONSerialization.jsonObject(with: response, options: .allowFragments) as? [String:Any] { 

       if let dataArray = (jsonData as AnyObject).value(forKey: "users") as? [[String:Any]] { 
        for data in dataArray{ 
         let newUser = Users(data: data) 
         self.userList.append(newUser) 
         print(jsonData!) 
        } 
       } 
       OperationQueue.main.addOperation({ 
        for use in self.userList { 
         print(use.name ?? "") 
        } 

        //reload your table here 
        // use name in cell for row at index as user.name 
       }) 

       print(jsonData!) 
      } 
     } 
    }).resume() 
} 

和你User型號:

class Users: NSObject { 
var name: String? 

init(data:[String:Any]) { 
    super.init() 
    if let nameStr = data["name"] as? String { 
     self.name = nameStr 
    } 
} 

}

儘量不要使用NSDictionaryNSArray因爲都是舊的技術,去爲新的[],[:]

0

在Users類中,您需要傳遞json數據併爲類變量分配相應的數據。

import UIKit 
class Users: NSObject { 

    var name: String? 
    required init(dictionary: NSDictionary) { 
    super.init() 
    self.name = dictionary["name"] as? String ?? "" 
} 

} 

,你解析字典作爲

if let dataDict = data as? NSDictionary { 
        let users = Users.init(dictionary: dataDict) 
        if let title = dataDict.value(forKey: "name") { 

         self.namesArray.append(title as! String) 
        } 
} 
相關問題