Swift 3 GET请求无法显示返回值

时间:2017-06-20 18:35:53

标签: json cocoa swift3

尝试使用Swift 3和Xcode8发出GET请求,但没有太多的运气输出我从GET请求收到的数据到标签或文本字段中的Main.Storyboard我得到的是所有返回的JSON in Xcode8中的控制台。

我的请求在Xcode8中返回了一个JSON片段,我已在下面附上以供参考。我可以访问" @ encoding"和" @版本"但其他一切都无法访问,我无法弄清楚原因。如果这是一个基于Web的设置,我可以声明一个变量然后将它设置为someObject.petfinder [1] .shelters等......

这是我的代码发出请求,从输入字段获取一个zipcode,然后构建url并返回它然后使用NSDictionary。

我在控制台中收到的错误是:

"致命错误:在展开Optional值时意外发现nil 2017-06-20 12:15:49.392688 PetFinder [47445:9486946]致命错误:在展开可选值时意外发现nil"

 // SEND HTTP GET REQUEST

    // DEFINE SERVER SIDE SCRIPT URL
    let scriptUrl = "https://api.petfinder.com/"
    let methodType = "shelter.find"
    let apiKey = "?key=0000000000000000000000000"
    let urlWithParams = scriptUrl + methodType + apiKey + "&location=\(shelterZip)&format=json"


    // CREATE NSURL Object
    let myUrl = NSURL(string: urlWithParams)

    // CREATE URL REQUEST
    let request = NSMutableURLRequest(url:myUrl! as URL);

    // REQUEST METHOD - GET / POST
    request.httpMethod = "GET"

    // RUN HTTP REQUEST
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error \(error!)")
                return
        }

    // PRINT OUT RESPONSE STRING
    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(String(describing: responseString))")


    // CONVERT RECEIVED JSON TO NSDictionary
        do {
            if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {

                // Print out dictionary
                print(convertedJsonIntoDict)

                // Get value by key
                let shelterName = convertedJsonIntoDict["shelters"] as? [String: Any]

                for(key, pair) in convertedJsonIntoDict {
                    print("-->\(key) \(pair)")
                }
                print(shelterName!)

            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }

    task.resume()

    }

//从顶部返回JSON的内容

 {
"@encoding" = "iso-8859-1";
"@version" = "1.0";
petfinder =     {
    "@xmlns:xsi" = "http://www.w3.org/2001/XMLSchema-instance";
    "@xsi:noNamespaceSchemaLocation" = "http://api.petfinder.com/schemas/0.9/petfinder.xsd";
    header =         {
        status =             {
            code =                 {
                "$t" = 100;
            };
            message =                 {
            };
        };
        timestamp =             {
            "$t" = "2017-06-20T16:15:49Z";
        };
        version =             {
            "$t" = "0.1";
        };
    };
    lastOffset =         {
        "$t" = 25;
    };
    shelters =         {
        shelter =             (
                            {
                address1 =                     {
                };
                address2 =                     {
                };
                city =                     {
                    "$t" = Nebraska;
                };
                country =                     {
                    "$t" = US;
                };
                email =                     {
                    "$t" = "wooffun@woof.net";
                };
                fax =                     {
                };
                id =                     {
                    "$t" = NE117;
                };
                latitude =                     {
                    "$t" = "13.004";
                };
                longitude =                     {
                    "$t" = "-31.449";
                };
                name =                     {
                    "$t" = WOOF COMPANY;
                };
                phone =                     {
                };
                state =                     {
                    "$t" = NE;
                };
                zip =                     {
                    "$t" = 68001;
                };
            },

1 个答案:

答案 0 :(得分:0)

首先 - 和往常一样

  • 不要在Swift中使用NSDictionary。你扔掉了类型信息。
  • 如果有原生的Swift对应物,请不要使用NSURLNS(Mutable)URLRequest等基础课程。
  • GET请求根本不需要URLRequest,这是默认设置。

其次,出于方便原因,我们可以使用类型别名。

typealias JSONDictionary = [String:Any]

此代码应该提取您要查找的键和值

let scriptUrl = "https://api.petfinder.com/"
let methodType = "shelter.find"
let apiKey = "?key=0000000000000000000000000"
let urlWithParams = scriptUrl + methodType + apiKey + "&location=\(shelterZip)&format=json"

// CREATE NSURL Object
let myUrl = URL(string: urlWithParams)!

// RUN HTTP REQUEST
let task = URLSession.shared.dataTask(with: myUrl) { data, response, error in

    if error != nil {
        print("error \(error!)")
        return
    }

    // CONVERT RECEIVED JSON TO NSDictionary
    do {
        if let rootDictionary = try JSONSerialization.jsonObject(with: data!) as? JSONDictionary,
            let petfinder = rootDictionary["petfinder"] as? JSONDictionary {

            // Get value by key
            if let shelters = petfinder["shelters"] as? JSONDictionary,
                let shelter = shelters["shelter"] as? [JSONDictionary] {

                for item in shelter {
                    for (key, value) in item {
                        print("-->\(key) \(value)")
                    }
                }
            }
        }

    } catch {
        print(error.localizedDescription)
    }
}
task.resume()