Alamofire 4.0和Swfit 3的词典

时间:2017-07-19 03:49:11

标签: json dictionary swift3 alamofire jsonresponse

我正在使用此代码并在打印时排队(jsonResponse [" data"]),我会非常快速,轻松地从API获得返回。

但是在第一个循环中我有一个无限循环。由于我的API返回,我需要执行此循环。

任何人都可以帮助我吗?我使用相同的代码来获取课程数据并填写一个tableview及其工作......但现在这个课程不适用于学校,我收到的API结构相同:

SWIFT CODE:

func findSchools(){
    let parameters: Parameters = [:]

    let headers: HTTPHeaders = [
        "ContentType": "application/json"
    ]

    API.consultAPI(headers: headers, type: .get, parameters: parameters, endpoint: "schools", completionSuccess: { (response) in

        if let responseValue: AnyObject = response.result.value as AnyObject? {
            let jsonResponse = JSON(responseValue)
            print(jsonResponse["data"])
            for (_, data) in jsonResponse["data"]{
                print(data)

                if data["id"] != nil && data["name"] != nil{
                    let school = School(id: data["id"].int!, name: data["name"].string!)
                    self.arraySchools.append(school)
                }

            }
        }
        print(self.arraySchools)

    }, completionFailure: {(response) in
        if let responseValue: AnyObject = response.result.value as AnyObject? {
            let jsonResponse = JSON(responseValue)
            print(jsonResponse)
            AlertView.showAlert(view: self, message: "Error")
        }
    })
}

API返回:

{  
"data":{  

 "0":{  
     "id":793,
     "name":"1",
     "default":false
  },

 "1":{  
     "id":3,
     "name":"2",
     "default":false
  },

  "2":{  
     "id":792,
     "name":"28",
     "default":false
  },
  "3":{  
     "id":5,
     "name":"3",
     "default":false
  },
  "4":{  
     "id":9,
     "name":"6",
     "default":false
  },
  "5":{  
     "id":795,
     "name":"793",
     "default":false
  },
  "6":{  
     "id":11,
     "name":"8",
     "default":false
  },
  "7":{  
     "id":4,
     "name":"aasdasdasd",
     "default":false
  },
  "8":{  
     "id":23,
     "name":"Abbotsleigh",
     "default":true
  },
  "9":{  
     "id":24,
     "name":"Academies Australiasia",
     "default":true
  },
  "10":{  
     "id":785,
     "name":"Acme labs",
     "default":false
  },
  "11":{  
     "id":25,
     "name":"Airds High School",
     "default":true
  },
  "12":{  
     "id":26,
     "name":"Al  Amanah College",
     "default":true
  },
  "13":{  
     "id":27,
     "name":"Albion Park High School",
     "default":true
  }
},

"links":[  

]
}

1 个答案:

答案 0 :(得分:0)

在代码中添加.dictionaryValue,现在它正在工作(没有无限循环):

const asyncSeries = require('async').series,
      asyncWhilst = require('async').whilst,
      mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.Promise = global.Promise;
mongoose.set('debug', true);

const uri = 'mongodb://localhost/test',
      options = { useMongoClient: true };

const tokenSchema = new Schema({
  token: { type: Number, unique: true },
  maxUse: Number
});

const Token = mongoose.model('Token', tokenSchema);

// Logger helper

function log(data) {
  console.log(JSON.stringify(data,undefined,2))
}


// Function implementation
function generateToken(maxUse) {
  const min = 100000000000;
  const max = 999999999999;
  const token =  Math.floor(Math.random() * (max -min) + min);

  return ({ token, maxUse });
}

// Main program
(async function() {

  try {
    const conn = await mongoose.connect(uri,options);

    console.log("Using async/await");
    // clean data
    await Promise.all(
      Object.keys(conn.models).map(m => conn.models[m].remove({}))
    );

    let count = 0,
        seenTokens = [],
        ops = [];

    while ( count < 500 ) {
      const maxUse = Math.floor(Math.random() * 5) + 1;

      let token = generateToken(maxUse);

      if ( seenTokens.indexOf(token.token) === -1 ) {
        seenTokens.push(token.token);
        ops.push(token);
        count++

        if ( count % 500 === 0 ) {
          await Token.insertMany(ops);
          ops = [];
        }
      } else {
        continue
      }

    }

    if ( count % 500 !== 0 ) {
      await Token.insertMany(ops);
      ops = [];
    }

    totalCount = await Token.count();
    console.log("Count is: %s", totalCount);

    // using async.whilst and indeed async.series for control
    console.log("using asyc.whilst");
    await Promise.all(
      Object.keys(conn.models).map(m => conn.models[m].remove({}))
    );

    await new Promise((resolve,reject) => {
      count = 0,
      seenTokens = [],
      ops = [];

      asyncSeries(
        [
          (callback) =>
            asyncWhilst(
              () => count < 500,
              (callback) => {
                const maxUse = Math.floor(Math.random() * 5) + 1;

                let token = generateToken(maxUse);

                if ( seenTokens.indexOf(token.token) === -1 ) {
                  seenTokens.push(token.token);
                  ops.push(token);
                  count++;

                  if ( count % 500 === 0 ) {
                    Token.insertMany(ops,(err,response) => {
                      console.log(count);
                      ops = [];
                      callback(err);
                    });
                  } else {
                    callback();
                  }
                } else {
                  console.log("trying again: seen token %s", token.token);
                  callback();
                }
              },
              callback
            ),

          (callback) => {
            if ( count % 500 !== 0 ) {
              Token.insertMany(ops,callback)
            } else {
              callback()
            }

          }
        ],
        (err) => {
          if (err) reject(err);
          ops = [];
          resolve();
        }
      );

    });

    totalCount = await Token.count();
    console.log("Count is: %s", totalCount);


  } catch (e) {
    console.error(e);
  } finally {
    mongoose.disconnect();
  }

})();