获取NSuserDefault中的json结果,并在Swift中的MapKit中显示注释结果

时间:2021-09-06 00:43:24

I want to get result from json and save this result in NSUserDefault, after I want to use the json array saved in NSUserDefault to add multiple annotation on the MapKit. Currently to get json result, I use this : ( Swift 2.x )

我希望从json获得结果并将此结果保存在NSUserDefault中,之后我想使用NSUserDefault中保存的json数组在MapKit上添加多个注释。目前为了获得json结果,我用这个:( Swift 2.x)

         let defaults = NSUserDefaults.standardUserDefaults()

    //Get user content//
   let url = NSURL(string: "http://www.example.com/folder/coordonate.php")
    let request = NSMutableURLRequest(URL: url!)

    // modify the request as necessary, if necessary

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if data == nil {
            print("request failed \(error)")
            return
        }

        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print(json)
                // print : {tab = "[london,paris]";}


                var test = json["tab"]

                defaults.setObject(test, forKey: "annotation") as? NSArray



                         }
        } catch {
            print(error)
        }
    }
    task.resume()
    NSUserDefaults.standardUserDefaults().synchronize()

And to get the NSUserdefault in another view, I try this code :

要在另一个视图中获取NSUserdefault,我尝试以下代码:

  let defaults = NSUserDefaults.standardUserDefaults()

    let test = NSUserDefaults.standardUserDefaults().objectForKey("annotation") as! NSArray
    map.addAnnotations(test as! [MKAnnotation])
    print("We saved this data: \(test)")
    //No print, error before

But I have an error when I try with this method.

但是当我尝试使用这种方法时,我有一个错误。

Could not cast value of type '__NSCFString' (0x1971a3958) to 'NSArray' (0x1971a4308).

3 个解决方案

#1


0  

If the "tab" property JSON actually being returned is:

如果实际返回的“tab”属性JSON是:

[london, paris]

Then the property is not an array. What you're looking for would be:

然后该属性不是数组。您正在寻找的是:

['london', 'paris']

But additionally I can tell you that even if the "tab" property is a properly formatted JSON array your code will fail when it attempts to convert it to [MKAnnotation] anyway. That's because iOS's JSON library does not know how to convert a generic NSArray into it's typed equivalent. The NSJSONSerialization documentation indicates all the types that JSON will convert to. Best case scenario the "tab" property is an array of items with the same structure as MKAnnotation and are being converted to an array of dictionaries that you will have to convert to MKAnnotation yourself. But the JSON provided currently evaluates as a string. With my suggested change it will instead evaluate to an array of strings- still not sufficient to create an MKAnnotation from.

但另外我可以告诉你,即使“tab”属性是格式正确的JSON数组,你的代码也会在尝试将其转换为[MKAnnotation]时失败。那是因为iOS的JSON库不知道如何将通用NSArray转换为它的类型等效。 NSJSONSerialization文档指出JSON将转换为的所有类型。最佳情况下,“tab”属性是一个与MKAnnotation具有相同结构的项目数组,并且正在转换为您必须自己转换为MKAnnotation的字典数组。但是当前提供的JSON评估为字符串。根据我建议的更改,它将改为评估为一个字符串数组 - 仍然不足以从中创建MKAnnotation。

#2


0  

Your JSON data has to be one of the valid NSUserDefault types (String, NSArray, NSDictionary, NSData).

您的JSON数据必须是有效的NSUserDefault类型之一(String,NSArray,NSDictionary,NSData)。

The quickest fix would be to store the JSON in NSUserDefaults as the NSData that comes back from the server. Then deserialize the NSData on the reading of NSUserDefaults.

最快的解决方法是将JSON存储在NSUserDefaults中,作为从服务器返回的NSData。然后在读取NSUserDefaults时反序列化NSData。

If storing a subset of the JSON from the server is really needed, I would use Dictionaries, Arrays and validate the data before storing it. As a general Swift rule, I avoid using NSDictionary and NSArray to ensure the types are what I expect and won't cause a runtime crash.

如果真的需要从服务器存储JSON的子集,我会使用字典,数组并在存储之前验证数据。作为一般的Swift规则,我避免使用NSDictionary和NSArray来确保类型符合我的预期,并且不会导致运行时崩溃。

#3


0  

change your php code to

将您的PHP代码更改为

$results = Array("tab" => ["london","paris"]);

instead of

$results = Array("tab" => "[london,paris]");

p.s if using php earlier than 5.5 (or 5.4 not quite remember) then use:

如果使用早于5.5的PHP(或5.4不太记得),那么使用:

$results = Array("tab" => Array("london","paris"));

==========================

you are casting the setObject func to NSArray and not the test object

您正在将setObject func转换为NSArray而不是测试对象

defaults.setObject(test, forKey: "annotation") as? NSArray

should be

if let arrayTest = test as? NSArray{
     defaults.setObject(arrayTest, forKey: "annotation")
} 

#1


0  

If the "tab" property JSON actually being returned is:

如果实际返回的“tab”属性JSON是:

[london, paris]

Then the property is not an array. What you're looking for would be:

然后该属性不是数组。您正在寻找的是:

['london', 'paris']

But additionally I can tell you that even if the "tab" property is a properly formatted JSON array your code will fail when it attempts to convert it to [MKAnnotation] anyway. That's because iOS's JSON library does not know how to convert a generic NSArray into it's typed equivalent. The NSJSONSerialization documentation indicates all the types that JSON will convert to. Best case scenario the "tab" property is an array of items with the same structure as MKAnnotation and are being converted to an array of dictionaries that you will have to convert to MKAnnotation yourself. But the JSON provided currently evaluates as a string. With my suggested change it will instead evaluate to an array of strings- still not sufficient to create an MKAnnotation from.

但另外我可以告诉你,即使“tab”属性是格式正确的JSON数组,你的代码也会在尝试将其转换为[MKAnnotation]时失败。那是因为iOS的JSON库不知道如何将通用NSArray转换为它的类型等效。 NSJSONSerialization文档指出JSON将转换为的所有类型。最佳情况下,“tab”属性是一个与MKAnnotation具有相同结构的项目数组,并且正在转换为您必须自己转换为MKAnnotation的字典数组。但是当前提供的JSON评估为字符串。根据我建议的更改,它将改为评估为一个字符串数组 - 仍然不足以从中创建MKAnnotation。

#2


0  

Your JSON data has to be one of the valid NSUserDefault types (String, NSArray, NSDictionary, NSData).

您的JSON数据必须是有效的NSUserDefault类型之一(String,NSArray,NSDictionary,NSData)。

The quickest fix would be to store the JSON in NSUserDefaults as the NSData that comes back from the server. Then deserialize the NSData on the reading of NSUserDefaults.

最快的解决方法是将JSON存储在NSUserDefaults中,作为从服务器返回的NSData。然后在读取NSUserDefaults时反序列化NSData。

If storing a subset of the JSON from the server is really needed, I would use Dictionaries, Arrays and validate the data before storing it. As a general Swift rule, I avoid using NSDictionary and NSArray to ensure the types are what I expect and won't cause a runtime crash.

如果真的需要从服务器存储JSON的子集,我会使用字典,数组并在存储之前验证数据。作为一般的Swift规则,我避免使用NSDictionary和NSArray来确保类型符合我的预期,并且不会导致运行时崩溃。

#3


0  

change your php code to

将您的PHP代码更改为

$results = Array("tab" => ["london","paris"]);

instead of

$results = Array("tab" => "[london,paris]");

p.s if using php earlier than 5.5 (or 5.4 not quite remember) then use:

如果使用早于5.5的PHP(或5.4不太记得),那么使用:

$results = Array("tab" => Array("london","paris"));

==========================

you are casting the setObject func to NSArray and not the test object

您正在将setObject func转换为NSArray而不是测试对象

defaults.setObject(test, forKey: "annotation") as? NSArray

should be

if let arrayTest = test as? NSArray{
     defaults.setObject(arrayTest, forKey: "annotation")
}