我是swift 5的新手。我很难调用视图控制器文件中的函数:
func getJsonResultFromUrl (urlSrc: String, completion:@escaping (Arts)->()) {
if let url = URL(string: urlSrc) {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
var returnValue: Arts?
let decoder = JSONDecoder()
returnValue = try decoder.decode(Arts.self, from: data)
completion(returnValue!)
} catch {
fatalError("Couldn't parse (url) as (Arts.self):n(error)")
}
}
task.resume()
}
}
来自另一个类为的文件
import UIKit
class ListStockArticle: UITableViewController {
var datacell: (Arts) -> () = {_ in } // = 0
var url: String = ""
var nombreDeLigne: Int?
init() {
let urlPrefixLocal = "http://urlmasqued"
let urlPrefixRemote = "http://urlmasqued"
if self.url.validURL {
} else {
self.url = urlPrefixRemote + ajax
}
print(self.url)
let k: () = getJsonResultFromUrl(urlSrc: url, completion: (Arts) -> () )
print(k)
////// -> I have error : Editor placeholder in source file
/* getJsonResultFromUrl(urlSrc: self.url) { k in Arts()
// self.datacell = Arts
self.nombreDeLigne = k.count
}
*/
super.init(nibName:nil, bundle:nil) // *
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20 //self.nombreDeLigne
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "Test"
return cell
}
}
URL和从URL获取数据工作正常,但我如何从另一个页面调用函数?这个想法是得到一个产品列表,并为每个产品创建一个单元格。
我真的很感激你的帮助,这对我来说很奇怪。问候
试试这个:Singleton类
class SampleController {
private static var privateSharedInstance: SampleController?
static var sharedInstance: SampleController {
if privateSharedInstance == nil {
privateSharedInstance = SampleController()
}
return privateSharedInstance ?? SampleController()
}
private init() {
}
func getJsonResultFromUrl () {
}
}
用法:
override func viewDidLoad() {
super.viewDidLoad()
SampleController.sharedInstance.getJsonResultFromUrl()
}