问题描述
我正在将照片从一个点传送到另一个点。一切正常,但是我无法获得照片(文件)传输速度I.G网速。与MB类似,文件被传输。其次,我要获取该文件的大小。
我们正在使用MCSession
由于隐私原因,我不能在这里添加项目代码,但我将分享我遵循的引用GitHub项目。在项目中,我传递字符串,在我的情况下,它的照片。所有东西都是一样的。
我签入Stackoverflow,但没有找到任何准确答案!
引用项目链接:https://github.com/YogeshPateliOS/MultipeerConnectivity-.git谢谢!
推荐答案
tldr:如果您不想阅读冗长的说明并直接进入代码,下面的所有想法都汇集在一起,可以通过下载我的public repository进行测试,public repository我的public repository包含解释所有这些内容的注释。
以下是我关于如何实现这一点的建议
检查代码后,我看到您正在使用以下函数发送数据
func send(_ data: Data, toPeers peerIDs: [MCPeerID], with mode: MCSessionSendDataMode)
这没有什么问题,您确实可以将UIImage转换为数据对象并以此方式发送,它将正常工作。
但是,我认为您无法跟踪进度,并且MultiPeer不会向您提供使用此方法跟踪进度的任何委托。
相反,您只剩下另外两个选项。您可以使用
func session(_ session: MCSession,
didFinishReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID,
at localURL: URL?,
withError error: Error?)
或者您可以使用
func startStream(withName streamName: String,
toPeer peerID: MCPeerID) throws -> OutputStream
我将使用第一个选项,因为它更简单,但是我认为STREAM选项会给您带来更好的结果。您可以在此处阅读这两个选项:
Send Resource(我们将实现此选项)
第一步
我对您的原始代码进行了一些UI更新,添加了一个UIImageView向广告商(访客)显示传输的图像,并添加了一个UIButton开始从浏览器(主机)传输文件UIImageView有一个名为@IBOutlet weak var imageView: UIImageView!
的插座和一个针对UIButton的操作@IBAction func sendImageAsResource(_ sender: Any)
我还将一个名为image2.jpg的图像添加到我们将从宿主发送给来宾的项目中。
第二步
我还声明了几个附加变量
// 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
第三步
分别点击Guest和Host按钮,将主机和来宾设置为正常。之后,点击主机上的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
}
第四步
下一个函数由主机和来宾使用。来宾方面的事情稍后会有意义,但是对于主机来说,在步骤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
}
}
}
第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)
}
第6步
在来宾端运行代码和this is the end result (uploaded to youtube),这将在传输完成后显示进度和文件,并且在主机端也会显示相同的进度。
第7步
我没有实现这一点,但我相信这一点很简单:
可以根据主机计算文件大小,并且可以按照预期的大小将其作为消息发送给来宾
您可以计算以下文件的近似百分比通过将进度百分比乘以文件大小下载
可以根据传输开始到目前为止下载的数据量/经过的时间来计算速度
如果您觉得这些计算不直观,我可以尝试添加此代码。
更新
我已经更新了上述代码示例、GitHub repo和视频,以包含最后3个步骤,最终结果如下:
这篇关于多点连接-获取SWIFT 5中的文件传输(互联网)速度和文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!