多点连接 - 在 Swift 5 中获取文件传输(互联网)速度和文件大小

Yog*_*tel 7 wifi multipeer-connectivity mcsession swift swift5

我正在点对点传输照片。一切正常,但我无法获得照片(文件)传输速度和互联网速度。与MB 一样,文件也被传输。其次,我想获取该文件的大小。

我们使用数据格式传递照片MCSession

由于隐私原因,我无法在此处添加项目代码,但我将分享我关注的参考 github 项目。在项目中,我传递字符串,在我的例子中传递照片。所有的事情都是一样的。

我在 Stackoverflow 上查了一下,但没有找到任何准确的答案!

参考项目链接: https://github.com/YogeshPateliOS/MultipeerConnectivity-.git

谢谢你!

Sha*_*ank 11

TLDR:如果您不想阅读冗长的解释并直接阅读代码,那么下面的所有想法都汇集在一起​​,可以通过下载我的公共存储库进行测试,其中包含解释所有这些内容的注释。

所以这是我关于如何实现这一目标的建议

查看您的代码后,我发现您正在使用以下函数来发送数据

func send(_ data: Data, toPeers peerIDs: [MCPeerID], with mode: MCSessionSendDataMode)
Run Code Online (Sandbox Code Playgroud)

这没有任何问题,您确实可以将 UIImage 转换为 Data 对象并以这种方式发送它,它会起作用。

但是,我认为您无法跟踪进度,并且 MultiPeer 不会为您提供任何委托来使用此方法跟踪进度。

相反,您还有另外两个选择。你可以使用

func session(_ session: MCSession, 
             didFinishReceivingResourceWithName resourceName: String, 
             fromPeer peerID: MCPeerID, 
             at localURL: URL?, 
             withError error: Error?)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用

func startStream(withName streamName: String, 
                 toPeer peerID: MCPeerID) throws -> OutputStream
Run Code Online (Sandbox Code Playgroud)

我将使用第一个选项,因为它更简单,但我认为流选项会给你更好的结果。您可以在此处阅读这两个选项:

发送资源(我们将实现这个)

流媒体

步骤1

我通过添加 UIImageView 向广告商(访客)显示传输的图像和 UIButton 来启动从浏览器(主机)的文件传输,对原始代码进行了一些 UI 更新 多点连接文件传输进度示例项目故事板

UIImageView 有一个名为@IBOutlet weak var imageView: UIImageView!UIButton 的插座和一个操作@IBAction func sendImageAsResource(_ sender: Any)

我还在项目中添加了一个名为 image2.jpg 的图像,我们将从主机发送到访客。

第2步

我还声明了一些额外的变量

// Progress variable that needs to store the progress of the file transfer
var fileTransferProgress: Progress?
    
// Timer that will be used to check the file transfer progress
var checkProgressTimer: Timer?

// Used by the host to track bytes to receive
var bytesExpectedToExchange = 0
    
// Used to track the time taken in transfer, this is for testing purposes.
// You might get more reliable results using Date to track time
var transferTimeElapsed = 0.0
Run Code Online (Sandbox Code Playgroud)

步骤3

通过分别点击“访客”和“主机”按钮,正常设置主机和访客。之后,点击Send image as resource主机上的按钮,主机执行的操作如下:

// A new action added to send the image stored in the bundle
@IBAction func sendImageAsResource(_ sender: Any) 
{        
        // Call local function created
        sendImageAsResource()
}

func sendImageAsResource()
{
        // 1. Get the url of the image in the project bundle.
        // Change this if your image is hosted in your documents directory
        // or elsewhere.
        //
        // 2. Get all the connected peers. For testing purposes I am only
        // getting the first peer, you might need to loop through all your
        // connected peers and send the files individually.
        guard let imageURL = Bundle.main.url(forResource: "image2",
                                             withExtension: "jpg"),
              let guestPeerID = mcSession.connectedPeers.first else {
            return
        }
        
        // Retrieve the file size of the image
        if let fileSizeToTransfer = getFileSize(atURL: imageURL)
        {
            bytesExpectedToExchange = fileSizeToTransfer
            
            // Put the file size in a dictionary
            let fileTransferMeta = ["fileSize": bytesExpectedToExchange]
            
            // Convert the dictionary to a data object in order to send it via
            // MultiPeer
            let encoder = JSONEncoder()
            
            if let JSONData = try? encoder.encode(fileTransferMeta)
            {
                // Send the file size to the guest users
                try? mcSession.send(JSONData, toPeers: mcSession.connectedPeers,
                                    with: .reliable)
            }
        }
        
        // Ideally for best reliability, you will want to develop some logic
        // for the guest to respond that it has received the file size and then
        // you should initiate the transfer to that peer only after you receive
        // this confirmation. For now, I just add a delay so that I am highly
        // certain the guest has received this data for testing purposes
        DispatchQueue.main.asyncAfter(deadline: .now() + 1)
        { [weak self] in
            self?.initiateFileTransfer(ofImage: imageURL, to: guestPeerID)
        }
    }
    
func initiateFileTransfer(ofImage imageURL: URL, to guestPeerID: MCPeerID)
{
        // Initialize and fire a timer to check the status of the file
        // transfer every 0.1 second
        checkProgressTimer = Timer.scheduledTimer(timeInterval: 0.1,
                                                  target: self,
                                                  selector: #selector(updateProgressStatus),
                                                  userInfo: nil,
                                                  repeats: true)
        
        // Call the sendResource function and send the image from the bundle
        // keeping hold of the returned progress object which we need to keep checking
        // using the timer
        fileTransferProgress = mcSession.sendResource(at: imageURL,
                                          withName: "image2.jpg",
                                          toPeer: guestPeerID,
                                          withCompletionHandler: { (error) in
                                            
                                            // Handle errors
                                            if let error = error as NSError?
                                            {
                                                print("Error: \(error.userInfo)")
                                                print("Error: \(error.localizedDescription)")
                                            }
                                            
                                          })
}

func getFileSize(atURL url: URL) -> Int?
{
        let urlResourceValue = try? url.resourceValues(forKeys: [.fileSizeKey])
        
        return urlResourceValue?.fileSize
}
Run Code Online (Sandbox Code Playgroud)

步骤4

下一个功能由主机和访客使用。来宾会做出一些稍后有意义的事情,但是对于主机来说,在步骤 3 中,您在启动文件传输后存储了一个进度对象,并且启动了一个每 0.1 秒触发一次的计时器,因此现在实现计时器查询该进度对象,在UILabel中显示主机端的进度和数据传输状态

/// Function fired by the local checkProgressTimer object used to track the progress of the file transfer
/// Function fired by the local checkProgressTimer object used to track the progress of the file transfer
@objc
func updateProgressStatus()
{
        // Update the time elapsed. As mentioned earlier, a more reliable approach
        // might be to compare the time of a Date object from when the
        // transfer started to the time of a current Date object
        transferTimeElapsed += 0.1
        
        // Verify the progress variable is valid
        if let progress = fileTransferProgress
        {
            // Convert the progress into a percentage
            let percentCompleted = 100 * progress.fractionCompleted
            
            // Calculate the data exchanged sent in MegaBytes
            let dataExchangedInMB = (Double(bytesExpectedToExchange)
                                     * progress.fractionCompleted) / 1000000
            
            // We have exchanged 'dataExchangedInMB' MB of data in 'transferTimeElapsed'
            // seconds. So we have to calculate how much data will be exchanged in 1 second
            // using cross multiplication
            // For example:
            // 2 MB in 0.5s
            //  ?   in  1s
            // MB/s = (1 x 2) / 0.5 = 4 MB/s
            let megabytesPerSecond = (1 * dataExchangedInMB) / transferTimeElapsed
            
            // Convert dataExchangedInMB into a string rounded to 2 decimal places
            let dataExchangedInMBString = String(format: "%.2f", dataExchangedInMB)
            
            // Convert megabytesPerSecond into a string rounded to 2 decimal places
            let megabytesPerSecondString = String(format: "%.2f", megabytesPerSecond)
            
            // Update the progress an data exchanged on the UI
            numberLabel.text = "\(percentCompleted.rounded())% - \(dataExchangedInMBString) MB @ \(megabytesPerSecondString) MB/s"
            
            // This is mostly useful on the browser side to check if the file transfer
            // is complete so that we can safely deinit the timer, reset vars and update the UI
            if percentCompleted >= 100
            {
                numberLabel.text = "Transfer complete!"
                checkProgressTimer?.invalidate()
                checkProgressTimer = nil
                transferTimeElapsed = 0.0
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

步骤5

通过实现以下委托方法来处理接收者(来宾)端的文件接收

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID)
{
        // Check if the guest has received file transfer data
        if let fileTransferMeta = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Int],
           let fileSizeToReceive = fileTransferMeta["fileSize"]
        {
            // Store the bytes to be received in a variable
            bytesExpectedToExchange = fileSizeToReceive
            print("Bytes expected to receive: \(fileSizeToReceive)")
            return
        }
}

func session(_ session: MCSession,
             didStartReceivingResourceWithName resourceName: String,
             fromPeer peerID: MCPeerID,
             with progress: Progress) 
{
        
        // Store the progress object so that we can query it using the timer
        fileTransferProgress = progress
        
        // Launch the main thread
        DispatchQueue.main.async { [unowned self] in
            
            // Fire the timer to check the file transfer progress every 0.1 second
            self.checkProgressTimer = Timer.scheduledTimer(timeInterval: 0.1,
                                                           target: self,
                                                           selector: #selector(updateProgressStatus),
                                                           userInfo: nil,
                                                           repeats: true)
        }
}

func session(_ session: MCSession,
             didFinishReceivingResourceWithName resourceName: String,
             fromPeer peerID: MCPeerID,
             at localURL: URL?,
             withError error: Error?) 
{
        
        // Verify that we have a valid url. You should get a url to the file in
        // the tmp directory
        if let url = localURL
        {
            // Launch the main thread
            DispatchQueue.main.async { [weak self] in
                
                // Call a function to handle download completion
                self?.handleDownloadCompletion(withImageURL: url)
            }
        }
}

/// Handles the file transfer completion process on the advertiser/client side
    /// - Parameter url: URL of a file in the documents directory
    func handleDownloadCompletion(withImageURL url: URL) 
{ 
        // Debugging data
        print("Full URL: \(url.absoluteString)")
        
        // Invalidate the timer
        checkProgressTimer?.invalidate()
        checkProgressTimer = nil
        
        // Set the UIImageView with the downloaded image
        imageView.image = UIImage(contentsOfFile: url.path)
}
Run Code Online (Sandbox Code Playgroud)

步骤6

运行代码,这是来宾端的最终结果(上传到 youtube),传输完成后显示进度和文件,并且主机端也会显示相同的进度。

步骤7

我没有实现这个,但我相信这一点很简单:

  1. 文件大小可以从主机计算出来,并且可以作为关于预期大小的消息发送给访客

  2. 您可以通过将进度百分比乘以文件大小来计算已下载文件的大约百分比

  3. 速度可以根据传输开始以来下载的数据量/经过的时间来计算

如果您觉得这些计算并不简单,我可以尝试添加此代码。

更新

我已经更新了上述代码示例、github 存储库和视频,以包含最后 3 个步骤,最终结果如下:

iOS MultiPeer 文件传输,显示进度、传输状态和传输速度