I configured the input stream to send the image to the http server, but I encountered an error: 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.And the path is not allowed to visit.
How can i solve the problem?
I made the following settings, you may receive an error message if you follow these steps:
1. Create and paste the code below into your project, install Alamofire
2. Drag the image with the name shot.png(you can take a screenshot and rename it to "shot.png") into your project.
3. Launch Xcode and tap the screen after it starts and get an error message in the console!
import UIKit
import Alamofire
class ViewController: UIViewController {
var customInputStream:InputStream?
let sourceFileName = "shot.png"
let destinationUrlString = "http://httpbin.org/stream/:11"
let bufferSize = 1048576
let path = Bundle.main.path(forResource: "shot.png", ofType: nil)!
var fileData = NSData()
var dataLength = 0
var fileSize:Int64 = 0
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{
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 {
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
case Stream.Event.endEncountered:
aStream.close()
aStream.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
case Stream.Event.errorOccurred:
print("error occurs!")
default:
break
}
}
}
}