试图解析json得到错误:使用未声明的类型' Foundation'

时间:2016-06-12 18:22:24

标签: ios json swift asynchronous

当我尝试解析JSON时,我遇到了这个奇怪的错误。我通过异步调用进行api调用,以获得城市slug,并使用完成处理程序:

//Load cities slug via api call
        let apiCall : webApi = webApi()

        apiCall.loadCitySlugs(){(success) in
            //Slug loaded in background
            //Call google api to compare the slug
            apiCall.compareSlugFromGoogleApi()    

在函数compareSlugFromGoogleApi()中有一些配置,比如异步调用的url,post params,所以除了异步调用函数之外没什么真正相关的:

/**
 Simple async call. Returns json NSMutableArray as AnyObject
 */
func asyncCall(url : String, completed : complHandlerAsyncCall)/* -> AnyObject*/{

    //Set async call params
    let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    request.HTTPMethod = "POST"

    request.HTTPBody = postParam.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {
            // check for fundamental networking error
            print("error=\(error)")
            return
        }
        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }


        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

        asyncJson = responseString?.parseJSONString as! NSMutableArray

        flagAsyncCall = true // true if download succeed,false otherwise

        completed(success: flagAsyncCall!)

    }
    task.resume()
    //return json! as AnyObject
}

在异步调用函数中,我调用一个扩展parseJSONString,它返回一个易于解析的json对象:

extension NSString
{
    var parseJSONString: AnyObject?
    {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

        if let jsonData = data
        {
            // Will return an object or nil if JSON decoding fails
            do
            {
                let message = try NSJSONSerialization.JSONObjectWithData(jsonData, options:.MutableContainers)
                if let jsonResult = message as? NSMutableArray
                {

                    return jsonResult //Will return the json array output
                }
                else
                {
                    return nil
                }
            }
            catch let error as NSError
            {
                print("An error occurred: \(error)")
                return nil
            }
        }
        else
        {
            // Lossless conversion of the string was not possible
            return nil
        }
    }
}

这就是我在使用Google电话时遇到问题的地方。一切看起来或多或少都没问题,但它从扩展中返回一个nil值然后,在异步调用中,它会抛出这个错误:

enter image description here

仍然是响应对象不为空:

enter image description here

2 个答案:

答案 0 :(得分:0)

它会抛出一个错误,因为L = [a,b,c] # List of input arrays out = (np.diff(np.vstack(L).reshape(len(L),-1),axis=0)==0).all() 返回nil,当你打开parseJSONString时它会崩溃。您应该检查!是否返回非零。 parseJSONString

答案 1 :(得分:-1)

使用NSDictionary代替NSMutableArray