JSON应用程序没有响应Web代码

时间:2016-02-08 10:59:45

标签: javascript ios json swift uitableview

我写了一些JSON代码,将其上传到我的FTP服务器,并在我的JSON应用程序中使用它。我还在Xcode中为我的应用编写了代码。我用Swift。问题是当我运行我的应用程序时,UITableView中没有返回任何内容。如何使文本显示在我的iOS模拟器中?

更新

我遵循了Scriptable的指导,这是我在Xcode中的新错误:

  

错误域= NSCocoaErrorDomain代码= 3840“字符0周围的值无效。” UserInfo = {NSDebugDescription =字符0周围的值无效。}

更新已结束

这是我的JSON Web代码(在.json文件中):

         {"items":[{

            "title" : "Big Little Lies Book Review",
            "date" : "WEDNESDAY 3RD FEBRUARY, 2016",
            "content" : "Few spoilers ahead. I finished reading Big Little Lies by Liane Moriarty a few days ago, and I haven't stopped thinking about it since! The book is so gripping,and the characters (what I love most) are so different. You have Madeline Mackenzie, a bubbly, bright 40 year old; Celeste White, a beautiful, weak lady who is married to a rich businessman; and Jane Chapman, a quiet, 24-year old mum with a mysterious past. The novel is set in Pirriwee, Australia. These characters' children all join Pirriwee Public, beginning Kindergarden. A previous orientation day drama still lingers between the mothers, especially the victim's mum, Renata Klein, and the so-called bully's mum, Jane (at this point, we still are unaware of who the bully is.) The story leads up to the annual trivia night of the school, with the end of each chapter showing a small extract of other mothers recounting the night. A detective is questioning them regard to a murder. In these extracts, we see that there is a conflict between Madeline, Celeste, and Jane as one, and the other mothers (not as much the fathers.) Moriarty makes connections between each character, each conflict, and each personal story. As you read the book, you see these connections strengthening, then all being vividly bonded at the end. The themes of this book are bullying, domestic violence, and teenage problems. Some are clearer and more elaborate than others. She shows great research by reading various books on the topic of domestic violence, which is the burden on Celeste. Each main character (Jane, Celeste, and Madeline) portray their own emotional conflict, some being more able to share than others. In the end, these problems are solved, naturally, as they should, but one problem's answer is harsher than the others. My rating for this fantastic book would be 4.5 stars, and would recommend to older teenagers and adults. This book adaptation will look great on the big screen. Big Little Lies has been envisaged to be shown in early 2017 on HBO, and consists of 8 episodes."
        },{

            "title" : "New Allegiant poster released",
            "date" : "WEDNESDAY 3RD FEBRUARY, 2016",
            "content" : "A new Allegiant poster has been released, and I have added it to Photos. It shows Shailene's character Tris on a swirling staircase (much like a DNAstrand),and also Four (Theo James), Caleb Prior (Ansel Elgort), Christina (Zoe Kravitz), and Peter (Miles Teller.) The new slogan has also been added, saying 'Whatmakes us different ties us together.' Allegiant is out in cinemas on March 18th, 2016. Its world premiere is in New York, being on March 14th (This is not completely confirmed yet.)"
        },{

            "title" : "Allegiant stills released",
            "date" : "FRIDAY 29TH JANUARY, 2016",
            "content" : "Some more Allegiant stills have been released - as if we can't get enough! The two that we have obtained of Shailene's character, Tris, have been added to the Allegiant gallery in Photos."
        },{

            "title" : "New Big Little Lies behind the scenes photos",
            "date" : "FRIDAY 29TH JANUARY, 2016",
            "content" : "With an abundance of Big Little Lies photos, yet we have received more. Most of these are from the first scene of the book, where Shailene's character, Jane, meets Reese Witherspoon's character, Madeline. This is the last day of shooting until April. Filming is being shot in Monterey, California. Some of these photos have been added to the gallery."
        },{

            "title" : "The Divergent Fandom App",
            "date" : "FRIDAY 29TH JANUARY, 2016",
            "content" : "As if the fandom couldn't get any better, The Divergent Series released an app for the fandom to group on. This app contains the latest news and stills regarding the Divergent films. My user is @totallyshailene, feel free to contact me! Once again, Allegiant is out on March 18th, 2016, with it's world premiere happening in New York, but with no date yet announced."
        },{

            "title" : "More Big Little Lies news",
            "date" : "FRIDAY 22ND JANUARY, 2016",
            "content" : "Filming will continue for 'Big Little Lies' from January 25th to January 29th in Monterey, California. Filming will then return in April for two weeks and wrap in May. The show's executive producer has said that post-production would last for approximately six months, and the show would air in early 2017. 'Big Little Lies' is a book-to-tv adaptation, focusing on three mothers played by Shailene Woodley, Reese Witherspoon, and Nicole Kidman."
        },{

            "title" : "Allegiant twitter Q&A",
            "date" : "FRIDAY 22ND JANUARY, 2016",
            "content" : "We were all incredibly excited when The Divergent Series on Twitter (@Divergent) said that we would have a Q&A on Twitter with Shailene Woodley and Theo James (Tris and Four respectively.) Shai and Theo answered great questions, of which you can see on The Divergent Series' Twitter. Shailene talked about what we can look forward to in Allegiant, and also gave a few motivational words - as always! These short videos have been added to its gallery in Videos."
        },{

            "title" : "New Allegiant trailer released",
            "date" : "FRIDAY 22ND JANUARY, 2016",
            "content" : "With all the fans in great anticipation, new 'Allegiant' has been released! This shows more emotional scenes of Tris (Shailene Woodley) and Four (Theo James) and the futuristic society of what is beyond the wall. 'Allegiant' will be out in cinemas on March 18th, 2016. The new trailer has been added to 'Videos.'"
        },{

            "title" : "Big Little Lies has offically began filming",
            "date" : "SUNDAY 10TH JANUARY, 2016",
            "content" : "'Big Little Lies,' Shailene Woodley's new project, officially began filming in California on January 10th. We have also obtained many behind the scenes images of which I have uploaded to 'Photos.'"
        },{

            "title" : "42nd Annual People's Choice Awards",
            "date" : "WEDNESDAY 6TH JANUARY, 2016",
            "content" : "The 42nd Annual People's Choice Awards happened on Wednesday 6th January, 2016. Although Shai wasn't in attendence, she won the award for Choice Female Action Actress for 'Insurgent.' 'Insurgent' was also nominated for Choice Action Movie, but lost to 'Furious 7.' Once again, another successful night for Shailene!"
        }]}

这是我的JSON应用代码:

import UIKit

class NewsTableViewController: UITableViewController {

var siteURL = "http://annabellesykes.byethost11.com/shailenewoodleyfansappjson.html"
var items = [Item]()

override func viewDidLoad() {
    super.viewDidLoad()

   getLatestNews()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NewsTableViewCell

    // Configure the cell...
    cell.titleLabel.text = items[indexPath.row].title
    cell.dateLabel.text = items[indexPath.row].date
    cell.contentLabel.text = items[indexPath.row].content

    return cell
}

func getLatestNews() {

    let request = NSURLRequest(URL: NSURL(string: siteURL)!)
    let urlSession = NSURLSession.sharedSession()
    let task = urlSession.dataTaskWithRequest(request, completionHandler: {
        (data, response, error) -> Void in

        if let error = error {
            print(error)
            return
        }

        if let data = data {
            self.items = self.parseJsonData(data)

            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.tableView.reloadData()
            })
        }

    })

    task.resume()
}

func parseJsonData(data: NSData) -> [Item] {

    var items = [Item]()

    do {

        let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary

        let jsonItems = jsonResult?["items"] as! [AnyObject]
        for jsonItem in jsonItems {
            let item = Item()
            item.title = jsonItem["title"] as! String
            item.content = jsonItem["content"] as! String
            item.date = jsonItem["date"] as! String
            items.append(item)
        }

    } catch {
        print(error)
    }

    return items
}

2 个答案:

答案 0 :(得分:1)

好吧,我认为问题在于您认为您在问题上发布的第一个代码块是JSON吗?它不是,它的HTML和Javascript。这就是你的JSON解析器失败的原因。

你写了一个网页,而不是网络服务,它们是非常不同的东西。您有几个选择:

  • 阅读webservices并创建一个(推荐)
  • 使用HTML解析器,下载页面并取出您想要的位
  • 将HTML加载到网页浏览中并使用javascript来提取您想要的内容

最后两个只是为了完整起见,你应该选择第一个。

答案 1 :(得分:0)

您当前的代码只是一个网页,您可以创建一个服务器端脚本来生成并返回特定URL的有效JSON,或者您可以创建一个.json文件。

例如:

创建一个名为example.json的空白文件,并在其中加入以下内容

 {
"items": [{
    "title": "Allegiant stills released",
    "date": "FRIDAY 29TH JANUARY, 2016",
    "content": "Some more Allegiant stills have been released - as if we can't get enough! The two that we have obtained of Shailene's character, Tris, have been added to the Allegiant gallery in Photos."
}, {
    "title": "Allegiant stills released",
    "date": "FRIDAY 29TH JANUARY, 2016",
    "content": "Some more Allegiant stills have been released - as if we can't get enough! The two that we have obtained of Shailene's character, Tris, have been added to the Allegiant gallery in Photos."
}, {
    "title": "Allegiant stills released",
    "date": "FRIDAY 29TH JANUARY, 2016",
    "content": "Some more Allegiant stills have been released - as if we can't get enough! The two that we have obtained of Shailene's character, Tris, have been added to the Allegiant gallery in Photos."
}, {
    "title": "Allegiant stills released",
    "date": "FRIDAY 29TH JANUARY, 2016",
    "content": "Some more Allegiant stills have been released - as if we can't get enough! The two that we have obtained of Shailene's character, Tris, have been added to the Allegiant gallery in Photos."
}]

}

然后上传到您的服务器并在您的iOS应用程序中使用以下URL:

http://annabellesykes.byethost11.com/example.json

值得一提的是,您可以通过http://www.tutorialspoint.com/json/json_php_example.htm尝试“按需”生成JSON。它可能不是最好的教程,但应该给你一个很好的起点,并告诉你你想要的东西。

编辑:

此代码在本地工作..

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let request = NSURLRequest(URL: NSURL(string: "http://local.test-application/example.json")!)
        let urlSession = NSURLSession.sharedSession()
        let task = urlSession.dataTaskWithRequest(request, completionHandler: {
            (data, response, error) -> Void in

            if let error = error {
                print(error)
                return
            }

            if let data = data {

                do {

                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary

                    print(jsonResult)

                    let jsonItems = jsonResult?["items"] as! [String:AnyObject]
                    for jsonItem in jsonItems {
                        print(jsonItem)
                    }

                } catch {
                    print(error)
                }


            }

        })

        task.resume()

    }

使用此JSON文件:https://filetea.me/t1s5uHGTDlCRNudTgqIMT5Mqw

此外,如果您在项目中使用非HTTPS网址,则需要AllowArbitaryLoads ...请参阅http://iosdevtips.co/post/121756573323/ios-9-xcode-7-http-connect-server-error