Ios 如何将数据从一个viewcontroller传递到另一个viewcontroller,该viewcontroller是json格式的,需要在tableview中设置?
这是我的密码:Ios 如何将数据从一个viewcontroller传递到另一个viewcontroller,该viewcontroller是json格式的,需要在tableview中设置?,ios,swift,uitableview,Ios,Swift,Uitableview,这是我的密码: public func getMethod() -> Array<Any>{ var array = [Any]() let session = URLSession.shared let aURL = URL(string: baseUrl+month)! var request = URLRequest(url: aURL) request.setValue("application/json", forHTTPHea
public func getMethod() -> Array<Any>{
var array = [Any]()
let session = URLSession.shared
let aURL = URL(string: baseUrl+month)!
var request = URLRequest(url: aURL)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(UserDefaults.standard.string(forKey: Actoken)!)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
array = [json]
print(array)
print(json)
} catch {
print("Could not serialise")
}
})
print(array)
task.resume()
return array
}
但当我尝试在另一个视图控制器中返回时,它返回的是null值。
如果不是这样的话,我该怎么做呢。
我需要将派生的json插入到表视图中。对于任何异步操作,都应该使用
completion
,因此您的代码应该如下所示:
class classA {
public func getMethod(completion: @escaping (_ resultArray: [Any])->()) {
var array = [Any]()
let session = URLSession.shared
let aURL = URL(string: baseUrl+month)!
var request = URLRequest(url: aURL)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(UserDefaults.standard.string(forKey: Actoken)!)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
array = [json]
completion(array)
}
catch {
print("Could not serialise")
}
})
task.resume()
}
}
//打电话的人应该是
let yourClass = classA()
yourClass.getMethod { [weak self] (resultArr) in
DispatchQueue.main.async {
let classB = ClassB()
classB.resultArray = resultArr
self?.navigationController.pushViewController(classB, animated: true)
}
}
一旦使用结果数组将其推送到classB,您就可以解析JSON响应并填充到tableView中。将闭包传递到getMethod中,该方法将在收到响应时执行。在闭包内部,使用json更新tableview的数据源,然后重新加载数据
public func getMethod(completion: (yourCustomType)->() ) {
...
let task = session.dataTask(with: request,
completionHandler: {(data, response, error) in
if let data = data {
do {
let json = try JSONDecoder.decode(yourCustomType.self, data)
completion(json)
}catch {
...
}
}
})
task.resume()
}
getMethod() { (responseData: YourCustomType) in
tableviewDatasource = responseData
DispatchQueue.main.async{
self.tableview.reloadData
}
}
异步编程不是这样工作的 您正在进行异步调用(
session.dataTask
调用),并希望同步返回结果。调用函数可能在网络调用完成之前读取结果。您应该使用闭包(完成块)
下面是一些演示异步模型的简单代码:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let Actoken = "SOMETHING"
public func getMethod(baseUrl:String, month:String, completion:@escaping (Array<Any>?)->()){
var array = [Any]()
let session = URLSession.shared
guard let aURL = URL(string: baseUrl+month) else {
print("invalid url")
completion(nil)
return
}
var request = URLRequest(url: aURL)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
do {
if let data = data {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
array = [json]
completion(array)
} else {
completion(nil)
}
}
catch {
print("Could not serialise")
completion(nil)
}
})
task.resume()
}
// here's how you call it from the view controller
getMethod(baseUrl: "https://mobilesecurity.win/sample.json", month: "") { array in
if let array = array {
print(array)
} else {
print("array was nil")
}
}
导入UIKit
导入PlaygroundSupport
PlaygroundPage.current.NeedsDefiniteExecution=true
让Actoken=“某物”
public func getMethod(baseUrl:String,month:String,completion:@escaping(Array?)->()){
变量数组=[Any]()
让session=URLSession.shared
guard let aURL=URL(字符串:baseUrl+month)else{
打印(“无效url”)
完成(无)
回来
}
var-request=URLRequest(url:aURL)
request.setValue(“application/json”,forHTTPHeaderField:“Accept”)
request.setValue(“application/json”,forHTTPHeaderField:“Content Type”)
让task=session.dataTask(带:request,completionHandler:{(数据,响应,错误))在
做{
如果let data=data{
让json=try JSONSerialization.jsonObject(with:data,options:JSONSerialization.ReadingOptions.allowFragments)
数组=[json]
完成(数组)
}否则{
完成(无)
}
}
抓住{
打印(“无法序列化”)
完成(无)
}
})
task.resume()
}
//下面是如何从视图控制器调用它
getMethod(baseUrl:)https://mobilesecurity.win/sample.json,月份:){中的数组
如果让数组=数组{
打印(数组)
}否则{
打印(“数组为零”)
}
}
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let Actoken = "SOMETHING"
public func getMethod(baseUrl:String, month:String, completion:@escaping (Array<Any>?)->()){
var array = [Any]()
let session = URLSession.shared
guard let aURL = URL(string: baseUrl+month) else {
print("invalid url")
completion(nil)
return
}
var request = URLRequest(url: aURL)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
do {
if let data = data {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
array = [json]
completion(array)
} else {
completion(nil)
}
}
catch {
print("Could not serialise")
completion(nil)
}
})
task.resume()
}
// here's how you call it from the view controller
getMethod(baseUrl: "https://mobilesecurity.win/sample.json", month: "") { array in
if let array = array {
print(array)
} else {
print("array was nil")
}
}