TLDR:如果您不想阅读冗长的解释并直接进入代码,下面的所有想法都汇集在一起,可以通过下载我的进行测试公共存储库 https://github.com/shawn-frank/MultiPeer-Progress-iOS其中有评论来解释这一切。
所以这是我关于如何实现这一目标的建议
查看您的代码后,我发现您正在使用以下函数来发送数据
func send(_ data: Data, toPeers peerIDs: [MCPeerID], with mode: MCSessionSendDataMode)
这没有任何问题,您确实可以将 UIImage 转换为 Data 对象并以这种方式发送它,它会起作用。
但是,我认为您无法跟踪进度,并且 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
我将使用第一个选项,因为它更简单,但我认为流选项会给你更好的结果。您可以在此处阅读这两个选项:
发送资源 https://developer.apple.com/documentation/multipeerconnectivity/mcsession/1407056-sendresource(我们将实现这一点)
流媒体 https://developer.apple.com/documentation/multipeerconnectivity/mcsession/1407071-startstream
Step 1
I made some UI updates to your original code by adding a UIImageView to show the transferred image to the advertiser(guest) and a UIButton to start the file transfer from the browser(host)
UIImageView 有一个名为@IBOutlet weak var imageView: UIImageView!
以及 UIButton 的操作@IBAction func sendImageAsResource(_ sender: Any)
我还在项目中添加了一个名为 image2.jpg 的图像,我们将从主机发送到访客。
Step 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
Step 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
}
Step 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
}
}
}
Step 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)
}
Step 6
运行代码并这是最终结果(上传到youtube) https://youtu.be/Ug4gJ67B6Vw在传输完成后,在来宾端显示进度和文件,并且在主机端也会显示相同的进度。
Step 7
我没有实现这个,但我相信这一点很简单:
-
文件大小可以从主机计算出来,并且可以作为关于预期大小的消息发送给访客
-
您可以计算已被删除的文件的大约百分比
通过将进度%乘以文件大小来下载
-
速度可以根据传输开始以来下载的数据量/经过的时间来计算
如果您觉得这些计算并不简单,我可以尝试添加此代码。
Update
我已经更新了上述代码示例、github 存储库和视频,以包含最后 3 个步骤,最终结果如下: