我已配置输入流以将图像传输到http服务器,但我遇到错误:Assertion failed: (CFReadStreamGetStatus(_stream.get()) == kCFStreamStatusNotOpen), function bodyStartProvidingData_block_invoke, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/CFNetwork/CFNetwork-811.4.18/HTTP/Core/IO/HTTPTransaction.cpp, line 2122.
并且不允许访问路径。
我该如何解决这个问题?
我已完成以下配置,如果您按照以下步骤操作,则可以收到错误消息:
1.将下面的代码复制并粘贴到您的项目中,安装Alamofire
2.拖放名为shot.png
的图像(您可以截取屏幕截图并将其重命名为' shot.png')到您的项目中。
3.运行Xcode,并在启动后触摸屏幕,并在控制台中收到错误消息!
import UIKit
import Alamofire
class ViewController: UIViewController {
var customInputStream:InputStream?
let sourceFileName = "shot.png"
let destinationUrlString = "http://httpbin.org/stream/:11"
///buffer size
let bufferSize = 1048576 //1024 * 1024
let path = Bundle.main.path(forResource: "shot.png", ofType: nil)!
//binary data of the file
var fileData = NSData()
//size of the data
var dataLength = 0
var fileSize:Int64 = 0
///inputstream counter
var readedBytes = 0
var sendedByteIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named: path)!
fileData = UIImagePNGRepresentation(image)! as NSData
dataLength = fileData.length
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
setUpInStreamForFile(path: path)
let url = URL(string: destinationUrlString)
let request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30)
Alamofire.upload(customInputStream!, with: request).response { (response) in
print("response:\(response)")
}
}
}
extension ViewController:StreamDelegate{
// MARK: - InputStream
func setUpInStreamForFile(path:String) -> () {
customInputStream = InputStream(fileAtPath: path)
customInputStream?.delegate = self
customInputStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
customInputStream?.open()
}
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
print("eventCode:\(eventCode)")
if aStream is InputStream {
switch eventCode {
// has data to read
case Stream.Event.openCompleted, Stream.Event.hasBytesAvailable:
readedBytes += sendedByteIndex
var length = (dataLength - readedBytes) >= bufferSize ? bufferSize : (dataLength - readedBytes)
var buffer = [UInt8](repeatElement(0, count: length))
fileData.getBytes(&buffer, range: NSRange(location: readedBytes, length: bufferSize))
length = (aStream as! InputStream).read(&buffer, maxLength: bufferSize)
sendedByteIndex = length
//read to the end of the stream
case Stream.Event.endEncountered:
aStream.close()
aStream.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
//aStream = nil
case Stream.Event.errorOccurred:
print("error occurs!")
default:
break
}
}
}
}