2017-12-29 48 views
0

나는 이것이 매우 기본적인 질문이라고 생각하지만, 제대로 작동하지 않습니다. AWS S3에서 이미지를 다운로드 중입니다. 다운로드 진행 상황을 확인할 수 있으며 그에 따라 진행 변수를 업데이트 할 수 있습니다. 그러나이 변수를 기반으로 진행률 표시 줄에 애니메이션을 적용하는 방법을 찾을 수 없습니다. 다음과 같이iOS 순환 진행 막대를 사용하여 AWS S3을 다운로드하십시오.

(틀림없이 투박한) 코드는 다음과 같습니다

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    self.refresh() //re-gets user info. Having trouble with AWS randomly claiming I'm attempting to download using UnAuth even though I am logged in 
    tableView.deselectRow(at: indexPath, animated: true) 
    self.downloadProgressView.isHidden = false 
    self.proprietaryObject = proprietaryObjects[indexPath.row] 
    let expression = AWSS3TransferUtilityDownloadExpression() 
    expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: { 
     self.progress = progress 
    }) 
    } 

    let transferUtility = AWSS3TransferUtility.default() 
    let resource = "\(self.proprietaryObject?.value1 ?? "NA")_\(self.proprietaryObject?.value2 ?? "NA")_\(self.proprietaryObject?.firstName ?? "NA")_\(self.proprietaryObject?.lastName ?? "NA")" 
    let type = "jpeg" 
    self.downloadingFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(resource).\(type)") 
    transferUtility.download(to: self.downloadingFileURL!, bucket: AWSS3BucketName, key: "\(resource).\(type)", expression: expression, completionHandler: { (task, URL, Data, Error) in 
     if Error != nil { 
      print (Error!) 
     } 
     if let data = Data { 
      print("Data: \(data)") 
      let image = UIImage(data: data) 
      self.downloadedImage = image 
     } 
    }).continueWith(executor: AWSExecutor.default()) { (task) -> Any? in 
     if let error = task.error { 
      print("download error: \(error)") 
      self.refresh() 
     }else { 
      print("Download started") 
      print("User: \(self.user?.username ?? "NO USER")") 
      self.animatePath() 

     } 
     return nil 
    } 
} 
func animatePath() { 
    print("Animation Started") 
    if !(self.view.subviews.contains(downloadProgressView)) { 
     self.view.addSubview(downloadProgressView) 
     downloadProgressView.center = self.view.center 
     self.downloadProgressView.isHidden = false 
     self.downloadProgressView.layer.addSublayer(self.shapeLayer) 
    }else { 
     self.view.bringSubview(toFront: self.downloadProgressView) 
     self.downloadProgressView.isHidden = false 
     downloadProgressView.center = self.view.center 
     if !((downloadProgressView.layer.sublayers?.contains(self.shapeLayer))!) { 
      self.downloadProgressView.layer.addSublayer(self.shapeLayer) 
     } 

    } 
    func animate() { 
     if self.progress?.fractionCompleted == nil { 
      self.fraction = 0 
     }else { 
      self.fraction = 0 + (self.progress?.fractionCompleted)! 
     } 
     let animation = CABasicAnimation(keyPath: "strokeEnd") 
     animation.fromValue = CGFloat(self.shapeLayer.strokeEnd) 
     animation.toValue = CGFloat(self.fraction!) 
     animation.duration = 0.2 
     animation.fillMode = kCAFillModeForwards 
     self.shapeLayer.strokeEnd = CGFloat(self.fraction!) 
     self.shapeLayer.add(animation, forKey: "animation") 
    } 

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1) , execute: { 
     //the one second delay gives self.progress.fractionCompleted time to be non-nil 
     repeat { 
      animate() 
      print("Completed: \((self.progress?.fractionCompleted)! * 100)%") 
     } while self.fraction! < 1 

     if self.fraction == 1 { 
      print("fraction achieved 100%. resetting to 0%") 
      self.fraction = 0 
      self.progress = nil 
      self.performSegue(withIdentifier: "proprietarySegue", sender: self) 
     } 
    }) 
} 

콘솔은 증분이 % 잘 ".fractionCompleted"그것은 100 %에 도달 할 때이 SEGUE을 수행하지 않습니다 기록합니다. 다음 ViewController의 UIImageView에있는 이미지는 실제로 다운로드 한 이미지입니다 (표시되지 않는 segue에 대한 덮어 쓰기). 그러나 나는 진도 원만 깜박입니다. 대개 진행 상황이 나타나지 않아서 segue를 수행합니다. 첫 번째 섹 션 직후마다 이후 다운로드 할 때마다 downloadProgressView가 나타나지 않거나 사라지기 전에 100 % 완료를 표시합니다.

나는 근본적으로 잘못된 것을하고 있거나 스레드와 관련이 있다는 느낌이 들었습니다 ...?

도움을 주시면 감사하겠습니다.

답변

0

self.animatePath()은 완료 블록 transferUtility에서 호출되었습니다. 그렇기 때문에 다운로드가 끝나면 애니메이션이 재생되고 연속 재생이 수행됩니다.

시도 :

let expression = AWSS3TransferUtilityDownloadExpression() 
expression.progressBlock = {(task, progress) in 
    DispatchQueue.main.async(execute: { 
     self.progress = progress 
     self.animatePath() 
    }) 
} 
+0

이 그 것이었다. 고마워, Vineet! animatePath() 호출을 진행 블록으로 이동하고 반복 애니메이션 블록을 제거했습니다. 또한 기술적으로 불필요하지만 1 초의 지연 시간을 남겨 두었습니다.이 경우에는 없기 때문에 더 깨끗해 보입니다. 또한 "self.fape == 1"블록에 "self.shapeLayer.strokeEnd = 0"을 추가해야했습니다. – End3r117