这个想法是使用“回调”。
在这里,我为你想要得到的 NSArray 做了一个:
completion: (dataArray: NSArray)->()
我们创建一个函数来获取数组,并将此回调添加到函数的签名中:
func getDataArray(urlString: String, completion: (dataArray: NSArray)->())
一旦数组准备好,我们将使用回调:
completion(dataArray: theNSArray)
完整的函数如下所示:
func getDataArray(urlString: String, completion: (dataArray: NSArray)->()) {
if let url = NSURL(string: urlString) {
NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
if error == nil {
if let data = data,
json1 = NSString(data: data, encoding: NSUTF8StringEncoding),
data1 = json1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data1, options: [])
if let jsonArray = json as? NSArray {
completion(dataArray: jsonArray)
}
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("Error: no data")
}
} else {
print(error!.localizedDescription)
}
}.resume()
}
}
现在我们像这样使用这个函数,不再有异步问题:
getDataArray("http://192.1.2.3/PhpProject1/getFullJson.php") { (dataArray) in
for dataDictionary in dataArray {
if let notId = dataDictionary["ID"] as? String {
self.IdDEc.append(notId)
}
}
print("id out count = ", self.IdDEc.count)
}
Swift 3更新+修复和改进。
func getContent(from url: String, completion: @escaping ([[String: Any]])->()) {
if let url = URL(string: url) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error == nil {
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let content = json as? [[String: Any]] { // array of dictionaries
completion(content)
}
} catch {
// error while decoding JSON
print(error.localizedDescription)
}
} else {
print("Error: no data")
}
} else {
// network-related error
print(error!.localizedDescription)
}
}.resume()
}
}
getContent(from: "http://192.1.2.3/PhpProject1/getFullJson.php") { (result) in
// 'result' is what was given to 'completion', an array of dictionaries
for dataDictionary in result {
if let notId = dataDictionary["ID"] as? String {
// ...
}
}
}