我使用iOS 7的Multipeer連接框架在兩個設備之間發送文件。我使用NSStreams來傳輸文件,因爲我之前使用MCSession的sendData:toPeers:withMode進行的嘗試實際上是不可靠的。不幸的是,我得到的傳輸速度非常慢,大約100kb/s,這對於我正在處理的應用程序來說不起作用。這裏是我的輸入和輸出流委託方法,這是文件傳輸發生的地方。使用Multipeer連接框架緩慢文件傳輸
輸出流(在委託用於流)
...//previous code
case NSStreamEventHasSpaceAvailable: {
//we will only open the stream when we want to send the file.
NSLog(@"Stream has space available");
//[self updateStatus:@"Sending"];
// If we don't have any data buffered, go read the next chunk of data.
if (totalBytesWritten< outgoingDataBuffer.length) {
//more stuff to read
int towrite;
int diff = outgoingDataBuffer.length-packetSize;
if (diff <= totalBytesWritten)
{
towrite = outgoingDataBuffer.length - totalBytesWritten;
} else
towrite = packetSize;
NSRange byteRange = {totalBytesWritten, towrite};
uint8_t buffer[towrite];
[outgoingDataBuffer getBytes:buffer range:byteRange];
NSInteger bytesWritten = [outputStream write:buffer maxLength:towrite];
totalBytesWritten += bytesWritten;
NSLog(@"Written %d out of %d bytes",totalBytesWritten, outgoingDataBuffer.length);
} else {
//we've written all we can write about the topic?
NSLog(@"Written %d out of %d bytes",totalBytesWritten, outgoingDataBuffer.length);
[self endStream];
}
// If we're not out of data completely, send the next chunk.
} break;
輸入流
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
NSLog(@"Bytes Available");
//Sent when the input stream has bytes to read, we need to read bytes or else this wont be called again
//when this happens... we want to read as many bytes as we can
uint8_t buffer[1024];
int bytesRead;
bytesRead = [inputStream read:buffer maxLength:sizeof(buffer)];
[incomingDataBuffer appendBytes:&buffer length:bytesRead];
totalBytesRead += bytesRead;
NSLog(@"Read %d bytes, total read bytes: %d",bytesRead, totalBytesRead);
}break;
case NSStreamEventEndEncountered:
{
UIImage *newImage = [[UIImage alloc]initWithData:incomingDataBuffer];
[[self.detailViewController imageView] setImage:newImage];
NSLog(@"End Encountered");
[self closeStream];
//this should get called when there aren't any more bytes being sent down the stream
}
}
}
有一種方法,以加快通過任一多線程或使用稍微改性NSStream子類此文件傳輸那使用異步套接字?
你還在瀏覽同行嗎?這篇文章(http://mzsanford.com/blog/ios7-multipeer-wifi-slow/index.html)討論了瀏覽/廣告如何影響你的整體wifi性能。另外,你是否有從設備到模擬器的工作?我可以從Sim轉到Device,但是當我嘗試發送給Sim時,我的輸入流會嘗試讀取一次數據,並找到零數據,然後斷開連接。 – Brian
嘿Brian。我的設置由兩個運行分開的應用程序執行文件傳輸的ipad mini組成。在瀏覽器和廣告客戶連接後,我仍然在瀏覽同行,因爲當我停止瀏覽同行時,我失去了與設備的連接。在使用sendData:toPeers方法時,我遇到了頻繁斷開連接的類似問題。這就是爲什麼我切換到使用Stream方法。 –
這只是奇怪,因爲從設備到設備的空中下載工作如此之快,但執行文件傳輸非常慢。蘋果必須爲其自身的實現做一些幕後魔法。 –