我有一个Mappable类型的模型,我在firstViewController中从api传递数据。现在我想访问secondViewController中的模型类数据。那么我如何在secondViewController中使用数据。 这是我的代码:
import ObjectMapper
class UserProfileResponse: Mappable {
var data:UserProfileData?
var success: Bool?
var error: String?
required init?(map: Map){
}
func mapping(map: Map) {
data <- map["data"]
success <- map["success"]
error <- map["error"]
}
}
class UserProfileData: Mappable {
var address: String?
var joinDate: String?
var phone: String?
var policyName: String?
var imageUrl: String?
var name: String?
var policyNo: String?
var title: String?
required init(map: Map){
}
func mapping(map: Map) {
address <- map["address"]
joinDate <- map["joinDate"]
phone <- map["phone"]
policyName <- map["policyName"]
imageUrl <- map["imageUrl"]
name <- map["name"]
policyNo <- map["policyNo"]
title <- map["title"]
}
}
我的FirstViewController,我将数据发送到此模型类
func getUserProfileDataFromApi(){
//Calling the method from Api class
userProfileApi{completion in self.getProfileData(result: completion)}
}
func userProfileApi(completion:@escaping (_ result:UserProfileData)->()) {
let defaultObject = UserDefaults.standard
let headerToken = defaultObject.object(forKey: KHeaderToken) as! String
let headers = ["Authorization": headerToken]
Alamofire.request(KProfileUrl, method: .post, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseObject{ (response: DataResponse<UserProfileResponse>) in
switch response.result{
case .success:
let value = response.result.value
completion((value?.data)!)
case .failure(let error):
print(error.localizedDescription)
}
}
}
func getProfileData(result: UserProfileData){
// Here i get all data in firstViewController
}
Now how i can get the UserProfileData in secondViewController.
答案 0 :(得分:0)
如果你使用segue从firstViewController显示secondViewController,那么你可以使用prepare segue来传递数据。
override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
let destinationViewController = segue.destination as! SecondViewController
destinationViewController.userProfileData = self.userProfileData
}
然后你的secondViewController就像这样,额外的实现。
class SecondViewController{
var userProfileData:UserProfileData?
}
答案 1 :(得分:0)
创建一个Signleton类,您可以在其中从API响应中填充UserProfileData。
Diff= c(0.0,1.7,3.2,-0.7,-1.0,2.2,-2,-0.9)
s <- data.frame(Diff)
# define indexes of subgroups of consecutive positive or negative numbers
RLE <- rle(Diff>=0)
RLE$values <- 1:length(RLE$values)
subgrps <- inverse.rle(RLE)
# aggregate by subgroups, create indexes or zero for each subgroup and add to the data.frame
s$Expected_Seq <- unlist(tapply(Diff,INDEX=subgrps,function(x) ifelse(x < 0,0,1:length(x))))
> s
Diff Expected_Seq
1 0.0 1
2 1.7 2
3 3.2 3
4 -0.7 0
5 -1.0 0
6 2.2 1
7 -2.0 0
8 -0.9 0
你可以从这个单例中访问userProfileData,但只有在你第一次退出并且启动它时才会这样做。不会在那里将你的信息存储在UserDefaults中。