这个问题在这里已有答案:
我从url获取json数据,我想从函数返回变量并再次使用它
internal func getJson(urlGet:String, urlData:String){
let urlFind = URL(string: urlGet)
var request = URLRequest(url: urlFind!)
request.httpMethod = "POST"
request.httpBody = urlData.data(using: .utf8)
var firstDataGet = [firstData]()
URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
print(urlGet)
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:String]
print(json)
} catch let error as NSError {
json = nil
}
}).resume()
return json
}
和viewcontroller的用法:
let result = getJsonLogin.getJson(urlGet: AppDelegate.ADDRESS+"/index.php", urlData: "mobile="+mobile+"")
print(result["message"])
我是初学者,我没有能解决这个问题
URLSession
请求是异步的。
因此,您需要设置回调以检索数据。像这样:
internal func getJson(urlGet: String, urlData: String, completion: @escaping ([String:String]?) -> Void) {
let urlFind = URL(string: urlGet)
var request = URLRequest(url: urlFind!)
request.httpMethod = "POST"
request.httpBody = urlData.data(using: .utf8)
var firstDataGet = [firstData]()
URLSession.shared.dataTask(with:request, completionHandler: { (data, response, error) in
guard let data = data, error == nil else { return }
print(urlGet)
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:String]
print(json)
completion(json)
} catch let error as NSError {
json = nil
completion(nil)
}
}).resume()
}
let result = getJsonLogin.getJson(urlGet: AppDelegate.ADDRESS+"/index.php", urlData: "mobile="+mobile+"") { result in
print(result)
}
当然,你可以(并且可能应该)更好地处理错误,而不仅仅是传递nil
。但为了简单起见,我只是添加了我能想到的最简单的方法,以解决您的问题。