以正确的方式上传/下载多张图片?

我正在尝试使用Nuke (用于下载和缓存图像的框架)和Firebase上传或下载图像作为后端上传图像

对于单个文件,它很容易处理没有任何问题,但对于多个我真的不知道该怎么做正确我有一个问题,它没有同步工作它下载第二个图像之前有时

我将展示下载和上传多个图像的方式

为了下载,我把代码放在for循环中

func downloadImages(completion: (result: [ImageSource]) -> Void){ var images = [ImageSource]() for i in 0...imageURLs.count-1{ let request = ImageRequest(URL: NSURL(string:imageURLs[i])!) Nuke.taskWith(request) { response in if response.isSuccess{ let image = ImageSource(image: response.image!) images.append(image) if i == self.imageURLs.count-1 { completion(result: images) } } }.resume() } } 

并且用于上传用户从图像选择器中选择图像的位置并将其作为NSData数组返回然后执行此代码

  func uploadImages(completion: (result: [String]) -> Void){ let storageRef = storage.referenceForURL("gs://project-xxxxxxxxx.appspot.com/Uploads/\(ref.childByAutoId())") var imageUrl = [String]() var imgNum = 0 for i in 0...imageData.count-1 { let imagesRef = storageRef.child("\(FIRAuth.auth()?.currentUser?.uid) \(imgNum)") imgNum+=1 let uploadTask = imagesRef.putData(imageData[i], metadata: nil) { metadata, error in if (error != nil) { print("error") imageUrl = [String]() completion(result: imageUrl) } else { print("uploading") // Metadata contains file metadata such as size, content-type, and download URL. let downloadURL = metadata!.downloadURL()?.absoluteString print(downloadURL) imageUrl.append(downloadURL!) if i == imageUrl.count-1{ //end of the loop print("completionUpload") completion(result: imageUrl) } } }} 

这是完成这项任务的好方法吗?

我应该怎么做才能使每个图像按顺序下载?

请给我任何可能有助于示例代码,链接等的内容。

提前致谢

我们强烈建议您同时使用Firebase存储和Firebase实时数据库来完成下载列表:

共享:

 // Firebase services var database: FIRDatabase! var storage: FIRStorage! ... // Initialize Database, Auth, Storage database = FIRDatabase.database() storage = FIRStorage.storage() 

上传:

 let fileData = NSData() // get data... let storageRef = storage.reference().child("myFiles/myFile") storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in // When the image has successfully uploaded, we get it's download URL let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString // Write the download URL to the Realtime Database let dbRef = database.reference().child("myFiles/myFile") dbRef.setValue(downloadURL) } 

下载:

 let dbRef = database.reference().child("myFiles") dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in // Get download URL from snapshot let downloadURL = snapshot.value() as! String // Now use Nuke (or another third party lib) let request = ImageRequest(URL: NSURL(string:downloadURL)!) Nuke.taskWith(request) { response in // Do something with response } // Alternatively, you can use the Storage built-ins: // Create a storage reference from the URL let storageRef = storage.referenceFromURL(downloadURL) // Download the data, assuming a max size of 1MB (you can change this as necessary) storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in // Do something with data... }) }) 

有关更多信息,请参阅零到应用程序:使用Firebase进行开发 ,以及它的相关源代码 ,以获取有关如何执行此操作的实际示例。