如何使用json而不是plist来填充TableView

时间:2016-08-18 11:12:57

标签: json uitableview swift2 plist

我有一个工作的应用程序,它从远程服务器上的pList获取数据。但是,我现在想使用json而不是plist,并且正在努力理解如何做到这一点!任何帮助非常感谢,任何例子都很棒。

一些选定的代码 - 首先下载plist,然后使用下载的plist填充TableView。注意:我没有包含所有代码。

@IBAction func startDownload(sender: AnyObject) {
progressView.hidden = false

    let url = NSURL(string: "http://ftp.iphoneData@dittodata.host-ed.me/Annotations/myAnnotationsKalkan.plist")!
    downloadTask = backgroundSession.downloadTaskWithURL(url)
    downloadTask.resume()
}

func showFileWithPath(path: String){
    let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path)
    if isFileFound == true{
        let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
        viewer.delegate = self
        viewer.presentPreviewAnimated(true)
       // print("file is found")
    }
}

@IBOutlet var progressView: UIProgressView!
 override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// 1
func URLSession(session: NSURLSession,
    downloadTask: NSURLSessionDownloadTask,
    didFinishDownloadingToURL location: NSURL){

    let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentDirectoryPath:String = path[0]
    let fileManager = NSFileManager()
    let destinationURLForFile = NSURL(fileURLWithPath: documentDirectoryPath.stringByAppendingString("/myAnnotationsKalkan.plist.plist"))

    if fileManager.fileExistsAtPath(destinationURLForFile.path!){
        showFileWithPath(destinationURLForFile.path!)
    }
    else{
        do {
            try fileManager.moveItemAtURL(location, toURL: destinationURLForFile)
//             show file
            showFileWithPath(destinationURLForFile.path!)
        }catch{
            print("An error occurred while moving file to destination url")
        }
    }
}

// 2
func URLSession(session: NSURLSession,
                downloadTask: NSURLSessionDownloadTask,
                didWriteData bytesWritten: Int64,
                             totalBytesWritten: Int64,
                             totalBytesExpectedToWrite: Int64){
    progressView.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
}

func URLSession(session: NSURLSession,
                task: NSURLSessionTask,
                didCompleteWithError error: NSError?){
    downloadTask = nil
    progressView.setProgress(0.0, animated: true)

    if (error != nil) {
        print(error?.description)
    }else{
      //  print("The task finished transferring data successfully")
         progressView.hidden = true
    }
}


//  TableViewController.swift
    /  museumTemplate

//

import UIKit


class MyTableViewController: UITableViewController {

var titleData = [String]()
var subTitleData = [String]()
var stateData = [String]()
var codeData = [String]()
var infoData = [String]()
var openData = [String]()
var phoneData = [String]()
var emailData = [String]()
var webData = [String]()
var latData = [Double]()
var lonData = [Double]()

var titleToPass = [String]()
var thisState = [String]()
var stateOrAlpha = ""
var titleText = ""


override func viewDidLoad() {
    super.viewDidLoad()

navigationItem.title = titleText

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    let sourcePath = documentsPath.stringByAppendingPathComponent("myAnnotationsKalkan.plist.plist")

    if let content = NSArray(contentsOfFile: sourcePath as String){


    let descriptor = NSSortDescriptor(key: stateOrAlpha, ascending: true)
    let myMuseum = content.sortedArrayUsingDescriptors([descriptor])

        for item in myMuseum{
                titleData.append(item.objectForKey("title") as! String)
                subTitleData.append(item.objectForKey("subtitle") as! String)
                infoData.append(item.objectForKey("info") as! String)
                phoneData.append(item.objectForKey("phone") as! String)
                webData.append(item.objectForKey("web") as! String)
                emailData.append(item.objectForKey("email") as! String)
                latData.append(item.objectForKey("latitude") as! Double)
                lonData.append(item.objectForKey("longitude") as! Double)
            }
        }
    }

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return titleData.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as UITableViewCell

    // Configure the cell..title and subTitle.
   cell.textLabel!.text = titleData[indexPath.row]
    return cell
    }

3 个答案:

答案 0 :(得分:1)

我使用Alamofire做Web请求更容易,更安全,但这里有一个没有它的代码:

 let urlPath = "YourUrlRequest"
            let session = NSURLSession.sharedSession()
            let url = NSURL(string: urlPath)!
            session.dataTaskWithURL(url) {( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

                if let  responseData = data {
                do {
                    let jsonObject = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as! NSArray
                    for dataDict : AnyObject in jsonObject {

                        let idj: String = dataDict.objectForKey("id") as!String
                        let namej: String = dataDict.objectForKey("name") as! String
                        let indicativej: String = dataDict.objectForKey("indicative") as! String
                        let flagj: String = dataDict.objectForKey("flag") as! String
                        saveCountryFromWeb(idj, name: namej, indicative: indicativej, flag: flagj)

                    }
                } catch let error as NSError {
                    print("Failed to load: \(error.localizedDescription)")
                }
                }

            }.resume()

希望有所帮助,告诉我如果你想要一个我推荐的alamofire样品;)

答案 1 :(得分:1)

func retrieveBarcodeData(){

    let databaseref = FIRDatabase.database().reference()
    databaseref.child("barcodes").queryOrderedByKey().observeEventType(.ChildAdded, withBlock: {
        snapshot in


        let codig = snapshot.value!["codigo"] as! String
        let desc = snapshot.value!["designacao"] as! String
        let Url = snapshot.value!["ImageURL"] as! String

        barcodes.insert(BarCodeStruct(code: codig, description: desc, ImageURL: Url),atIndex: 0)
        self.tableView.reloadData()



    })

}

不要忘记在firebase中配置数据库,并使用cocoapods安装firebase并将FIRApp.configure()放入appDelegate didFinishLaunchingWithOptions

答案 2 :(得分:0)

我尝试使用此代码从服务器下载一个简单的json文件,它似乎可以工作:

monitor.start(os.path.dirname(__file__))