swift var不会在块外更新

时间:2017-03-17 17:18:02

标签: swift firebase xcode8

我已从https://www.weheartswift.com/firebase-101/获取原始代码并进行了编辑,以满足我的需求。

在此视图控制器中,我更新图像,然后使用按钮执行展开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的值,那么没有任何事情发生,在那个块之外它可以工作但是我无法理解,因为我必须动态生成它...

有人能帮助我吗?

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
    }



}

1 个答案:

答案 0 :(得分:1)

我的猜测是unwind segue在put数据操作完成之前发生,而self.downloadURL在其他视图控制器读取时没有设置。

要检查这一点,您可以在put完成块中设置一个断点,在目标segue中设置一个断点。