swift 如何将日期组件转换为双精度以获得上传速度

swift how to convert date component in a double to get upload speed

我尝试通过 FTP 向服务器发送图像来检查上传速度,我知道它不是很清晰,但我别无选择。第一个问题是测试时间,这段代码总是给我 0 秒也许是对的也许不是,但是我什至无法将图像的大小(以 mb 为单位)除以时间(以秒为单位)的主要问题 id,因为经过的时间表示为dateComponent,怎么做?

使用此代码

func pushfileUpload() {
    print("uploading...")

    let startDate = NSDate()

    //*****************************************************************



    //find file in app bundle
    let imageChecked = findFileInBundle(nameWithNoEx: "image", extension: "jpg")
    //convert to Data
    let imageData = imageChecked.jpegData(compressionQuality: 1)
    //instanziate the class
    let ftpUploader = FTPUpload.init(baseUrl: Constants.kHostname, userName: Constants.kUsername, password: Constants.kPassword, directoryPath: Constants.kFolder)

    ftpUploader.send(data: imageData!, with: "image") { (result) in
        if result {
            print("result is \(result)")
        } else {
            print("no result")
        }
    }


    //*****************************************************************
    print("...uploaded")
    let endDate = NSDate()
    let difference = timeDifference(date1: startDate as Date, date2: endDate as Date)
//        print("Time difference is : \(difference)")


    //1 converto to string
    let differenceString = String(difference)
    //2 pick first 3 ints
    let array = differenceString.compactMap{Int(String([=11=]))}
    //3 create new int
    let newInt = array[0...3]

    var newString = ""
    for i in newInt {
        newString.append(i.description)
    }
    var fromIntToString = Int(newString)

    fromIntToString = fromIntToString! * 1000

    let speed = 1500 / fromIntToString!
    print("speed: \(speed)")



}





func timeDifference(date1: Date, date2: Date) -> Int {

    let calendar = NSCalendar.current
    var compos:Set<Calendar.Component> = Set<Calendar.Component>()
    //        compos.insert(.second)
    compos.insert(.nanosecond)
    let difference = calendar.dateComponents(compos, from: date1, to: date2)
    //        print("diff in seconds= \(difference.second!)") // difference in seconds
    print("diff in nanoseconds = \(difference.nanosecond!)") // difference in nanoseconds

    let newValue = difference.nanosecond!

    return newValue
}

//更新代码

func pushfileUpload() {
    print("uploading...")

    let startDate = Date()

    //*****************************************************************
    //find file in app bundle
    let imageChecked = findFileInBundle(nameWithNoEx: "image", extension: "jpg")
    //convert to Data
    let imageData = imageChecked.jpegData(compressionQuality: 1)
    //instanziate the class
    let ftpUploader = FTPUpload.init(baseUrl: Constants.kHostname, userName: Constants.kUsername, password: Constants.kPassword, directoryPath: Constants.kFolder)

    ftpUploader.send(data: imageData!, with: "image") { (result) in
        if result {
            print("result is \(result)")
            //-----------------------------------------------------
            //Your code to calculate elapsed time belongs here
            let endDate = Date()
            let elapsed = endDate.timeIntervalSinceReferenceDate -
                startDate.timeIntervalSinceReferenceDate
            print("The download took \(elapsed) seconds.")
            print("speed is \(1500 / elapsed)")
            //-----------------------------------------------------
        } else {
            print("no result")
        }
    }}

在控制台上打印

The download took 1.281269907951355 seconds.
speed is 1170.7135168720042

正如其他人所说,您需要将计算总时间的代码移到闭包中:

func pushfileUpload() {
    print("uploading...")

    let startDate = Date()

    //*****************************************************************
    //find file in app bundle
    let imageChecked = findFileInBundle(nameWithNoEx: "image", extension: "jpg")
    //convert to Data
    let imageData = imageChecked.jpegData(compressionQuality: 1)
    //instanziate the class
    let ftpUploader = FTPUpload.init(baseUrl: Constants.kHostname, userName: Constants.kUsername, password: Constants.kPassword, directoryPath: Constants.kFolder)

    ftpUploader.send(data: imageData!, with: "image") { (result) in
        if result {
            print("result is \(result)")
            //-----------------------------------------------------
            //Your code to calculate elapsed time belongs here
            let endDate = Date()
            let elapsed = endDate.timeIntervalSinceReferenceDate - 
               startDate.timeIntervalSinceReferenceDate
            print("The download took \(elasped) seconds."
            //-----------------------------------------------------
        } else {
            print("no result")
        }
    }

...

正如其他人所提到的,没有理由处理日期组件。 timeIntervalSinceReferenceDate 方法为您提供日期的双精度秒数,因此很容易对日期进行数学运算以找出它们之间的差异。您可以根据需要计算小数点后的差值。