I'm trying to pull web data to be placed in a tableview and custom cell in Swift.
My app dies at
if let tmpdata = response.data {
for entry in tmpdata.valueForKey("results") as! [NSDictionary] {
let musicTrack = MusicTrack(data: entry)
self.musicTracks.append(musicTrack)
}
Heres The code for my Music Manager.
import Foundation
import Alamofire
let musicUrl = "https://itunes.apple.com/search?term=one%20republic"
class MusicManager {
var musicTracks: [MusicTrack] = []
let session = NSURLSession.sharedSession()
func getMusicTracks(onComplete : (results :[MusicTrack]) -> Void) {
Alamofire.request(.GET, musicUrl).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
if let tmpdata = response.data {
for entry in tmpdata.valueForKey("results") as! [NSDictionary] {
let musicTrack = MusicTrack(data: entry)
self.musicTracks.append(musicTrack)
}
onComplete(results: self.musicTracks)
}
}
}
}
}
Then my ListViewController
import UIKit
class ListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let musicManager = MusicManager()
var musicTracks: [MusicTrack]!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 100
musicManager.getMusicTracks { (results) -> Void in
self.musicTracks = results
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(self.musicTracks != nil){
return self.musicTracks.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MusicCell = self.tableView.dequeueReusableCellWithIdentifier("musicCell") as! MusicCell
cell.posterImage.image = nil
let mTrack = self.musicTracks[indexPath.row]
let imagedata = NSData(contentsOfURL: NSURL(string: mTrack.thumbnail)!)
if let tmpdata = imagedata {
cell.posterImage.image = UIImage(data: tmpdata)
}
cell.artistName.text = mTrack.artistName
cell.trackName.text = mTrack.trackName
return cell
}
}
The error I get back is
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]:
this class is not key value coding-compliant for the key results.'
Any help or direction would be awesome.
Thank you!
I faced the similar problem to but i came up with a solution.
-> Add the below function to yourviewcontroller.swift file
func postWebserviceWithURL(strUrl: String, param: NSDictionary?, completionHandler: (NSDictionary?, NSError?) -> ()) -> (){
Alamofire.request(.POST, strUrl, parameters: param as? [String : AnyObject], encoding: ParameterEncoding.URL).responseJSON { response in
switch response.result {
case .Success(let data):
let json = data as? NSDictionary
completionHandler(json, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
}
-> then for calling the func/api, use below code
self.postWebserviceWithURL("passyourURL", param: parameters) { (response, error) -> () in
if error == nil{
print("success")
}
else {
print("failed")
}
}
else{
print("error")
}
}
Related
This is my netWorkOperations classs
import UIKit
class NetworkOpertions: NSObject {
private var actors = [Actor]()
func getMethod(OnCompletion:#escaping (Any)-> Void) {
guard let url = URL(string: "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors")else {return}
let session = URLSession.shared.dataTask(with:url){
(data,response,error) in
if let data = data {
print("This is Data:", data)
do{
let decoder = JSONDecoder()
let downloadedActors = try decoder.decode(Actors.self, from: data)
let res = data
}
OnCompletion(res)
}
catch let err{
print(err.localizedDescription)
// OnCompletion()
}
}
}
session.resume()
}
}
This is my ViewController class
import UIKit
class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate,UIPopoverPresentationControllerDel egate{
private var actors = [Actor]()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Welcome"
tableView.delegate = self
tableView.dataSource = self
downloadJson()
tableView.tableFooterView = UIView()
}
func downloadJson() {
let netWork = NetworkOpertions()
let reponseValue = netWork.getMethod(){ (fetchValue)-> Void in
Here its throwing error:Invalid conversion from throwing function of type '(_) throws -> Void' to non-throwing function type '(Any) -> Void'
if fetchValue != nil {
print("MY VAlue:",fetchValue)
let decoder = JSONDecoder()
let downloadedActors = try decoder.decode(Actors.self, from: data)
self.actors = downloadedActors.actors
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actors.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ActorCell") as? ActorCell else { return UITableViewCell() }
cell.nameLbl.text = actors[indexPath.row].name
cell.DOBLbl.text = actors[indexPath.row].dob
cell.countryCell.text = actors[indexPath.row].country
if let imageURL = URL(string: actors[indexPath.row].image) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.imgView.image = image
}
}
}
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
}
please help me how to solve this error:
Invalid conversion from throwing function of type '(_) throws -> Void'
to non-throwing function type '(Any) -> Void'
The reason of the error is the missing do catch block wrapping the decode line
do {
let downloadedActors = try decoder.decode(Actors.self, from: data)
self.actors = downloadedActors.actors
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch { print(error) }
I am new at Alamofire and I am following the book IOS Apps with REST APIs, where I try to parse JSON and populate the tableview but the problem is that it calls numberOfRowsInSection before the function loadGists finishes calling the Alamofire chained requests so I can populate the Array and then populate the tableview accordingly, it seems that .responseArray function is called Asynchronous or called after numberOfRowsInSection function.
var gists: [Gist]!
#IBOutlet var tabelView1: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tabelView1.delegate = self
self.tabelView1.dataSource = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
loadGists()
}
func loadGists() {
GitHubAPIManager.sharedInstance.getPublicGists() { result in
guard result.error == nil else {
print(result.error)
// TODO: display error
return
}
if let fetchedGists = result.value {
self.gists = fetchedGists
}
DispatchQueue.main.async {
self.tableView1.reloadData()
}
}
}
Where GitHubAPIManager Class has:
class GitHubAPIManager: NSObject {
static let sharedInstance = GitHubAPIManager()
func getPublicGists(completionHandler: (Result<[Gist]>) -> Void) {
Alamofire.request(GistRouter.GetPublic())
.responseArray { (response) in
completionHandler(response.result)
}
}
}
And responseArray is:
public func responseArray<T: ResponseJSONObjectSerializable>(
completionHandler: Response<[T]) -> Self {
let serializer = ResponseSerializer<[T]> { request, response, data, error in
guard error == nil else {
return .Failure(error!)
}
guard let responseData = data else {
let failureReason = "Array could not be serialized because input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed,
failureReason: failureReason)
return .Failure(error)
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response,
responseData, error)
switch result {
case .Success(let value):
let json = SwiftyJSON.JSON(value)
var objects: [T] = []
for (_, item) in json {
if let object = T(json: item) {
objects.append(object)
}
}
return .Success(objects)
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: serializer, completionHandler: completionHandler)
}
For table view:
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return gists.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let gist = gists[indexPath.row]
cell.textLabel!.text = gist.description
cell.detailTextLabel!.text = gist.ownerLogin
return cell
}
GistRouter is:
enum GistRouter: URLRequestConvertible {
static let baseURLString:String = "https://api.github.com"
case getPublic()
var method: HTTPMethod {
switch self {
case .getPublic:
return .get
}
}
func asURLRequest() throws -> URLRequest {
let result: (path: String, parameters: [String: AnyObject]?) = {
switch self {
case .getPublic:
return ("/gists/public", nil)
}
}()
let URL = Foundation.URL(string: GistRouter.baseURLString)!
var UrlRequest: URLRequest? = URLRequest(url: URL.appendingPathComponent(result.path))
UrlRequest = try URLEncoding.default.encode(UrlRequest!, with: result.parameters)
UrlRequest?.httpMethod = method.rawValue
return UrlRequest!
}
And Gist Class is:
class Gist: ResponseJSONObjectSerializable {
var id: String?
var description: String?
var ownerLogin: String?
var ownerAvatarURL: String?
var url: String?
required init(json: SwiftyJSON.JSON) {
self.description = json["description"].string
self.id = json["id"].string
self.ownerLogin = json["owner"]["login"].string
self.ownerAvatarURL = json["owner"]["avatar_url"].string
self.url = json["url"].string
}
required init() {
}
}
I have tried DispatchQueue.global(qos: .utility).async and also
let semaphore = DispatchSemaphore(value: 0) in different ways with no luck, I need to have Alamofire chained requests all done first and then numberOfRowsInSection called, please help.
It worked for me with:
var gists = [Gist]() {
didSet {
self.tabelView1.reloadData()
}
}
I have searched around to find an answer for my issue, but I had no luck. I'm new in coding, especially with Swift 3.0.
I'm trying to parse a YouTube playlist dynamically in a tableview using Alamofire cocoa pod in my project. My project contains: a viewcontroller called "videosViewController" which holds the tableview, a class called "Video", which holds the items I'm parsing from youtube API, and another class called "VideoModel" holds the method to pare those items. When I run my project the console parse the items successfully, but then the project crashes at the line of code:
for video in (data["items"] as? NSDictionary)!
with "Could not cast value of type '__NSArrayI' (0x10d2ebd88) to 'NSDictionary' (0x10d2ec288)." error as shown below
Project crash
Console details
And here the snippet of code I used:
videosViewController:
import UIKit
class videosViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var videos:[Video] = [Video]()
var selectedVideo: Video?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let model = VideoModel()
model.fetchVideos()
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return (self.view.frame.size.width / 320) * 180
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicCell")!
let videoTitle = videos[indexPath.row].videoTitle
let label = cell.viewWithTag(2) as! UILabel
label.text = videoTitle
let videoThumbnailUrlString = "https://i1.ytimg.com/vi/" + videos[indexPath.row].videoId + "/maxresdefault.jpg"
let videoThumbnailUrl = NSURL(string: videoThumbnailUrlString)
if videoThumbnailUrl != nil {
let request = URLRequest(url: videoThumbnailUrl! as URL)
let session = URLSession.shared
let task = session.dataTask(with: request,
completionHandler: { (data:Data?,
response:URLResponse?,
error:Error?) -> Void in
DispatchQueue.main.async {
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(data: data!)
}
})
task.resume()
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedVideo = self.videos[indexPath.row]
self.performSegue(withIdentifier: "goToDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailView = segue.destination as! videoDetailViewController
detailView.selectedVideo = self.selectedVideo
}
}
The Video class:
import UIKit
class Video: NSObject {
var videoId:String = ""
var videoTitle:String = ""
var videoDescription:String = ""
var videoThumbnailURL = ""
}
And the VideoModel class:
import UIKit
import Alamofire
class VideoModel: NSObject {
let parameters: Parameters = ["part":"snippet","playlistId":"PLMRqhzcHGw1ZRUB86rmNqG15Sr5jV-2NU","key":"AIzaSyDdNXhz3H7ifXB-qfOVakz0Xps2Y-kP0R0"]
var videoArray = [Video]()
func fetchVideos() {
Alamofire.request("https://www.googleapis.com/youtube/v3/playlistItems", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(let JSON):
print("Success with JSON: \(JSON)")
if let data = response.result.value as? [String: AnyObject] {
// print(response.result.value)
var arrayOfVideos = [Video]()
for video in (data["items"] as? NSDictionary)! {
let videoObj = Video()
videoObj.videoId = (video.value as? NSDictionary)?["snippet.resourceId.videoId"] as? String ?? ""
videoObj.videoTitle = (video.value as? NSDictionary)?["snippet.title"] as? String ?? ""
videoObj.videoDescription = (video.value as? NSDictionary)?["snippet.description"] as? String ?? ""
videoObj.videoThumbnailURL = (video.value as? NSDictionary)?["snippet.thumbnails.maxres.url"] as? String ?? ""
print(video)
// You need to parse the items into the video data
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
// }
}
case .failure(let error):
print("Request failed with error: \(error)")
}
}
}
Replace
as? NSDictionary
with
as? [String:Any]
in
for video in (data["items"] as? NSDictionary)!
Bcs: You have to cast type Any to Swift dictionary type [String:Any].
if let JSON = response.result.value as? [String : Any] {
if let items = JSON["items"] as? [[String : Any]] {
for video in items {
//Other code
}
}
}
I'm trying to parse data from this data source, Titles are parsed correctly and displayed, but the problem occurred when parsing the images, I got an error: “fatal error: unexpectedly found nil while unwrapping an Optional value”
Here is my Code:
ViewModel.swift
import Foundation
class ViewModel {
let urlString = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=30/json"
var titles = [String]()
var images = [String]()
func fetchTitles(success:() -> ()) {
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let url = NSURL(string: urlString)
let task = session.dataTaskWithURL(url!) { (data, response, error) -> Void in
let parser = JSONParser()
self.titles = parser.titlesFromJSON(data!)
success()
}
task.resume()
}
func fetchImages(success:() -> ()) {
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let url = NSURL(string: urlString)
let task = session.dataTaskWithURL(url!) { (data, response, error) -> Void in
let parser = JSONParser()
self.images = parser.imagesFromJSON(data!)
success()
}
task.resume()
}
func numberOfSections() -> Int {
return 1
}
func numberOfItemsInSection(section: Int) -> Int {
return titles.count
}
func titleForItemAtIndexPath(indexPath: NSIndexPath) -> String {
return titles[indexPath.row]
}
}
and MyTableViewController.swift
import UIKit
class MyTableViewController: UITableViewController {
let viewModel = ViewModel()
var imageCache = [String:UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
self.refresh()
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(MyTableViewController.refresh), forControlEvents: .ValueChanged)
}
func refresh() {
viewModel.fetchTitles {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
viewModel.fetchImages {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.viewModel.numberOfSections()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.numberOfItemsInSection(section)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTableViewCell
cell.songTitle.text = self.viewModel.titleForItemAtIndexPath(indexPath)
let urlString = self.viewModel.titleForItemAtIndexPath(indexPath)
//found nil
let imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if error == nil {
cell.songImage.image = UIImage(data: data!)
}
})
return cell
}
and JSONParser.swift
import Foundation
class JSONParser {
func titlesFromJSON(data: NSData) -> [String] {
var titles = [String]()
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject],
let feed = json["feed"] as? [String: AnyObject],
entries = feed["entry"] as? [[String: AnyObject]] {
for entry in entries {
if let name = entry["im:name"] as? [String: AnyObject],
label = name["label"] as? String {
titles.append(label)
}
}
}
} catch {
print("error parsing JSON: \(error)")
}
return titles
}
func imagesFromJSON(data: NSData) -> [String] {
var images = [String]()
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject],
let feed = json["feed"] as? [String: AnyObject],
entries = feed["entry"] as? [[String: AnyObject]] {
for entry in entries {
if let name = entry["im:image"]![0] as? [String: AnyObject],
label = name["label"] as? String {
images.append(label)
}
}
}
} catch {
print("error parsing JSON: \(error)")
}
return images
}
}
And I have a class MyTableViewCell subclass of UITableViewCell containing a UILabel and a UIImageView.
I can't figure out what's the problem, and why I'm getting this error. Thank you for your time.
I always recommend you to avoid the use of force-unwrapping and adopt a more secure way of code (e.g using optional binding) avoiding runtime errors. So you can change your code to the following code and avoid the runtime error:
for entry in entries {
if let name = entry["im:image"], let value = name[0] as? [String: AnyObject],
label = value["label"] as? String {
images.append(label)
}
}
In the above way you avoid the use of force-unwrapping.
I hope this help you.
Below is my ViewController code. The println in GetRequest prints the correct data that it receives from the HTTP GET request. At this point, tableData has 10 key-value pairs. However, if I put a break point after the call to GetRequest() in viewDidLoad(), tableData is empty and nothing is displayed in the tableView. Why is this? Where am I going wrong?
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
#IBOutlet var tableView: UITableView!
var tableData: [String:String] = [:]
let textCellIdentifier = "TextCell"
func GetRequest(urlPath: String)
{
var LatestWaitTimes: [String:String] = [:]
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err)
if err != nil {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
let json = JSON(jsonResult!)
let count: Int? = json.array?.count
if let ct = count {
for index in 0...ct-1 {
let name = json[index]["CrossingName"].string
var wait = json[index]["WaitTime"].stringValue
if (wait == "-1")
{
wait = "No Info"
}
else
{
wait += " min"
}
println(name!+": "+wait)
LatestWaitTimes[json[index]["CrossingName"].stringValue] = wait as String?
}
}
self.tableData = LatestWaitTimes
})
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
var apiInfo = GetWaitTimes()
GetRequest(apiInfo.BorderCrossingApi+"?AccessCode="+apiInfo.AccessCode)
self.tableView.delegate = self
self.tableView.dataSource = self
tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(self.textCellIdentifier) as! UITableViewCell
let thisEntry = self.tableData.values.array[indexPath.row]
cell.textLabel?.text = thisEntry+": "+tableData[thisEntry]!
return cell
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
The problem is that GetRequest runs asynchronously. So you have to reloadData inside the completionHandler of dataTaskWithURL:
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
// do all of your existing stuff here
dispatch_async(dispatch_get_main_queue()) {
self.tableData = LatestWaitTimes
self.tableView.reloadData()
}
})
task.resume()
You can remove the reloadData from within viewDidLoad.
Rearrange the orders of the method calls:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
var apiInfo = GetWaitTimes()
GetRequest(apiInfo.BorderCrossingApi+"?AccessCode="+apiInfo.AccessCode)
tableView.reloadData()
}
Explanation: you set the delegate and dataSource before you GetRequest() so the dataSource won't be nil.
Try this it may help you
you can add a callback (for reload tablview) in GetRequest function and run the callback after parser json in completionHandler
Maybe When you set the delegate with tableview, tableData still be nil (waitting for http response)
this is my code .you can refer to
demand.loadDataFromServer(self.view, done: { () -> Void in
self.demands = demand.getDemandDataList()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
})
func loadDataFromServer(view:UIView,done:(() -> Void)!){
var request:HttpRequest = HttpRequest(view:view)
request.GET(getDemandListURL, parameters: nil, success: { (dict) -> Void in
self.demandLists = dict["data"] as NSMutableArray
done()
}, failed: { (dict) -> Void in
}) { (error) -> Void in
}
}