A thread is loading an image from a package using swift3 gets an error

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"


///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
        }
    }
}  
}
+6

All Articles