我已采取https://www.weheartswift.com/firebase-101/的原始代码并进行编辑以适合我的需要。swift var不会在块之外更新
在这个视图控制器我更新一个图像,然后,我用一个按钮执行unwind segue和另一个视图控制器调用函数updateValues并将数据存储在firebase中。
什么不工作是updateValues功能,但仅适用于taskImg值,其他(taskTitle和taskLat和taskLon完美的作品)
我认为它不会更新,因为它的这个代码块
#里面self.storageRef.child(filePath).put(data as Data, metadata: metaData).observe(.success) { (snapshot) in
self.downloadURL = snapshot.metadata!.downloadURL()!.absoluteString
completion()
}
#
,因为如果我尝试任何var值从里面改什么也没有发生,该块它的工作原理之外,但obiouvsly我可以,因为我没有动态地生成它...
有人可以帮我吗?
func editImage(completion: @escaping callback){
let resizedImage = resizeImage(image: imagePicked.image!, newWidth: 200)
var data = NSData()
// data = UIImageJPEGRepresentation(imagePicked.image!, 0.1)! as NSData
data = UIImageJPEGRepresentation(resizedImage!, 0.1)! as NSData
let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/Pictures/\(NSUUID().uuidString)"
let metaData = FIRStorageMetadata()
//store downloadURL
metaData.contentType = "image/jpg"
self.storageRef.child(filePath).put(data as Data, metadata: metaData).observe(.success) { (snapshot) in
//progress upload
self.storageRef.child(filePath).put(data as Data, metadata: metaData).observe(.progress) { snapshot in
// Upload reported progress
if let progress = snapshot.progress {
let percentComplete = 100.0 * Double(progress.completedUnitCount)/Double(progress.totalUnitCount)
print("percent \(percentComplete)")
}
}
self.storageRef.child(filePath).put(data as Data, metadata: metaData).observe(.success) { snapshot in
// Upload completed successfully
print("success")
}
self.storageRef.child(filePath).put(data as Data, metadata: metaData).observe(.failure) { snapshot in
print(snapshot.error?.localizedDescription ?? "")
}
self.downloadURL = snapshot.metadata!.downloadURL()!.absoluteString
completion()
print(self.taskImg,"\"inside editImage function, right value")
}
}
func updateValues() {
self.taskTitle = self.titleField.text
if tapped == true {
self.taskLat = latitude
self.taskLon = longitude
}else{
//doesn't update location
}
self.taskCompleted = self.completedSwitch.isOn
if tappedpicture == true {
editImage { self.taskImg = self.downloadURL
print (self.downloadURL,"\"inside updateValues function, right value")
}
print (self.taskImg,"\"this is where i need it and it's wrong value")
}else{
//doesn't update location
}
}
什么是self.taskImg的类型?请提供课程定义。 – iphaaw
self.taskImg的类型是字符串 – HaVaNa7
您应该将该块视为一个单独的函数,在声明的打印范围超出范围之后,在稍后的运行循环中调用该块。我猜如果你在你的打印行上放置一个断点,然后在你的任务上放置一个断点(例如'self.taskImg = downloadURL'),你会看到'print'被首先调用。如果您在块内分配后立即调用print,则会看到使用更新的值调用它。一旦它具有正确的值,你想用'taskImg'变量做什么? –