Ios 从JSON解析返回数据-Swift

Ios 从JSON解析返回数据-Swift,ios,json,swift,Ios,Json,Swift,所以我是一个Swift的新手,而且有点像一般的编程。从今年第一年开始我就一直这么做。。。我试图制作一个简单的应用程序,从外部JSON文件中提取数据,并将其输入UILabels。我已经获取了要提取的数据,并将其附加到一个数组中。从这里开始,它似乎退出了范围,无法在其他任何地方使用。。。因此,我创建了一个用于保存数据的结构。如你所见,我添加了打印标记,以直观地查看正在发生的事情 struct GlobalTestimonialData { var testimonialsText

所以我是一个Swift的新手,而且有点像一般的编程。从今年第一年开始我就一直这么做。。。我试图制作一个简单的应用程序,从外部JSON文件中提取数据,并将其输入UILabels。我已经获取了要提取的数据,并将其附加到一个数组中。从这里开始,它似乎退出了范围,无法在其他任何地方使用。。。因此,我创建了一个用于保存数据的结构。如你所见,我添加了打印标记,以直观地查看正在发生的事情

  struct GlobalTestimonialData {
        var testimonialsText: [String]
        var customerNames: [String]
        var companyNames: [String]
    }

    var TestimonialData = GlobalTestimonialData(testimonialsText: [""], customerNames: [""], companyNames: [""])

    func getData () {
        let requestURL: URL = URL(string: "https://szadydesigns.com/test/mobileapp/testimonials.php")!
        let urlRequest = URLRequest(url: requestURL as URL) 
        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in

            let httpResponse = response as! HTTPURLResponse
            let statusCode = httpResponse.statusCode

    if (statusCode == 200) {
                print("File has been downloaded!")
                do {

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

                    print("JSON Serialized")

                    if let JSONfile = json as? [String: AnyObject] {
                        print("JSON Reading")
                        if let testimonial = JSONfile["testimonial"] as? [String] {
                            print("Testimonials Read")
                            TestimonialData.testimonialsText.append(contentsOf: testimonial)
                            print(TestimonialData.testimonialsText)
                            print("Inside of loop Testimonial Text Number: \(TestimonialData.testimonialsText.count)")

                            if let name = JSONfile["name"] as? [String] {
                                print("Names Read")
                                TestimonialData.customerNames.append(contentsOf: name)
                                print(TestimonialData.customerNames)
                                print("Inside of loop Customers Number: \(TestimonialData.customerNames.count)")
                            }
                            if let company = JSONfile["company"] as? [String] {
                                print("Companies Read")
                                TestimonialData.companyNames.append(contentsOf: company)
                                print(TestimonialData.companyNames)
                            }
                            print("Companies: \(TestimonialData.companyNames)")
                        }
                        print("COMPANIES: \(TestimonialData.companyNames)")
                    }
                    print("Companies AGIAN: \(TestimonialData.companyNames)")
                }catch {
                    print("Error with Json: \(error)")
                }
                print("Companies AGIAN AGAIN : \(TestimonialData.companyNames)")
            }
            print("Companies AGIAN AGAIN AGAIN: \(TestimonialData.companyNames)")
        }

        //Loses Scope
        print("Companies AGIAN TIMES : \(TestimonialData.companyNames)")
        task.resume()

        print("Outside of loop Customers Number: \(TestimonialData.customerNames.count)")
        print("Outside of loop Testimonial Text Number: \(TestimonialData.testimonialsText.count)")
        print(TestimonialData.companyNames)
    }

我知道我错过了一些非常简单的事情…但我不知所措。。。欢迎提供任何帮助/信息

此代码存在一些问题:

第一:您正在接收的JSON不是您的代码所期望的格式。根对象不是字典,而是数组

if let JSONfile = json as? [String: Any] {
更改为

if let JSONfile = json as? [[String: String]] {
这还要求您循环每个项目

print("JSON Reading")
for item in JSONfile {
由于词典定义已从
[String:Any]
更改为
[String:String]
As?字符串
语句也不再需要

第二:我不确定你是否意识到了这一点(也许你已经意识到了),但是
//失去作用域后的代码位首先运行。在
公司再次重新启用
公司再次启用
行之前

它们可能位于页面下方,但上面的行在文件下载后运行的闭包中,因此在其他行运行后执行


下面是完整的固定代码(格式化后,您可以将其复制并粘贴到Xcode中,以查看其工作情况)

您将得到这个输出,这有助于解释发生了什么(尽管我删除了实际的公司名称)


你在用故事板吗?您的代码不在链接到情节提要的任何自定义类中,因此我对如何显示数据感到困惑。您没有调用回调,因此
task.resume()
之后的打印行将始终不打印数据,因为
dataTask
是异步工作的。代码中还有一个很大的设计错误:一个自定义结构应该为每个证明创建一个实例,而不是保存多个数组。在Swift 3中,对JSON字典使用本机
URL
URLRequest
[String:Any]
。是的,我使用的是故事板。上面的代码位于它自己的.Swift文件中,以保持ViewController“干净”。您的问题是
requestURL
,似乎端点存在一些问题,是您的私有端点还是公共端点。如果我无法访问它。。。问题是,如果端点不好,您的json数据将始终为零,这就是为什么您无法更新
结构。。。所以仔细检查你的端点,我如何设置我的端点?对不起,如果我在这里迷路了…我真的迷路了。如果我在viewController中抛出所有当前代码,一切似乎都正常。我只是不想这样设置它,因为它是疯狂的混乱(我肯定这不是这样做的方式…)。
// Xcode 8.2, Swift 3
import Cocoa
import PlaygroundSupport

// Required for the download to work.
PlaygroundPage.current.needsIndefiniteExecution = true


struct GlobalTestimonialData {
    var testimonialsText: [String]
    var customerNames: [String]
    var companyNames: [String]
}

var testimonialData = GlobalTestimonialData(testimonialsText: [], customerNames: [], companyNames: [])

func getData () {
    let requestURL: NSURL = NSURL(string: "https://szadydesigns.com/test/mobileapp/testimonials.php")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) in

        let httpResponse = response as! HTTPURLResponse
        let statusCode = httpResponse.statusCode
        if (statusCode == 200) {
            print("File has been downloaded!")
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)

                print("JSON Serialized")

                if let JSONfile = json as? [[String: String]] {
                    print("JSON Reading")
                    for item in JSONfile {
                        if let testimonial = item["testimonial"] {
                            testimonialData.testimonialsText.append(testimonial)

                            if let name = item["name"] {
                                testimonialData.customerNames.append(name)
                            }
                            if let company = item["company"] {
                                testimonialData.companyNames.append(company)
                            }
                        }
                    }
                }
            } catch {
                print("Error with Json: \(error)")
            }
        }
        print("Companies Last: \(testimonialData.companyNames)")
        print(" ")
        print(testimonialData)
    }

    //Loses Scope
    print("Companies 1 : \(testimonialData.companyNames)")
    task.resume()

    print("Before the download of the JSON Customer names count: \(testimonialData.customerNames.count)")
    print("Before the download of the JSON Testimonial Text Number: \(testimonialData.testimonialsText.count)")
    print(testimonialData.companyNames)
}

getData()
Companies 1 : []
Before the download of the JSON Customer names count: 0
Before the download of the JSON Testimonial Text Number: 0
[]
File has been downloaded!
JSON Serialized
JSON Reading
Companies: ["REMOVED_1", "REMOVED_2", "REMOVED_3", "REMOVED_4"]