2017-12-12 9 views
0

이미지를 Firebase Storage에 업로드하고 해당 경로의 다운로드 URL을 반환하는 함수를 만들어서 앱의 다른 부분을 사용할 수 있도록하려고합니다.함수를 사용하여 Firebase 스토리지에서 downloadUrl을 반환하려고 시도했습니다.

func uploadImage(to reference:StorageReference, image:UIImage) -> URL? { 

     let imageData = UIImageJPEGRepresentation(image, 0.2) 
     let metadata = StorageMetadata() 
     metadata.contentType = "image/jpeg" 
     var downloadURL = metadata.downloadURL() 
     reference.putData(imageData!, metadata: metadata) { (metadata, error) in 
      if error != nil { 
       print("Couldnt upload due to \(String(describing: error))") 
      } 
      downloadURL = metadata?.downloadURL() 
     } 
     return downloadURL! 
    } 

내가 downloadUrl 항상 전무를 반환으로 내가 원하는 결과를 얻을 수없는 것 :

이 함수가 모습입니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

1

여기서 문제는 업로드가 완료되기 전에 함수가 반환된다는 것입니다. 즉, 함수는 일반 URL이 아닌 콜백을 반환해야합니다. ~

func uploadImage(to reference:StorageReference, image:UIImage, completion: @escaping (URL?) -> Void) { 
    let imageData = UIImageJPEGRepresentation(image, 0.2) 
    let metadata = StorageMetadata() 
    metadata.contentType = "image/jpeg" 
    var downloadURL = metadata.downloadURL() 
    reference.putData(imageData!, metadata: metadata) { (metadata, error) in 
     if error != nil { 
      print("Couldnt upload due to \(String(describing: error))") 
      completion(nil) 
     } else { 
      if let downloadUrl = metadata?.downloadURL() { 
       completion(downloadUrl) 
      } else { 
       completion(nil) 
      } 
     } 
    } 
} 
+0

안녕하세요 Chris 님, 답장을 보내 주셔서 감사합니다. UIImage를 매개 변수로 사용하고 Storage에 업로드 한 다음 업로드가 완료된 후 최종적으로 URL을 반환하는 함수를 사용할 수있는 다른 방법이 있습니까? – AAAM

+0

위 예제는 URL을 제공 할 것이므로 콜백을 사용해야합니다. https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html –

+0

https : // stackoverflow를 살펴보십시오. 익숙하지 않은 경우 Closure에 대한 Swift 문서를 살펴보십시오. 좀 더 일반적인 설명을 위해 비동기 적 호출/응답/14220321/i-return-the-return-the-asynchronous-call/14220323 # 14220323을 참조하십시오. –