How to request using Alamofire to get stream JSON. I am using the below function to get the response
self.sessionManager?.request(url, method: methodType!, parameters: params, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { (response) in
if (response.result.error == nil) {
completion(response.result.value as AnyObject?, nil , response.response?.statusCode )
} else {
// debugPrint("HTTP Request failed: \(String(describing: response.result.error))")
completion(nil, response.result.error, response.response?.statusCode)
}
}
And my API Url something like
http://{server Url}/services/data/{number of chunks}/{items in per chunk}
and the response I get from API if the number of chunks is 3 and items per chunk is 3
data: [
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026419,
},
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
},
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
}
]
data: [
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
},
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
},
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
}
]
data: [
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
},
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
},
{
"invalidDraft": false,
"bulkReserve": false,
"srNo": 0,
"returned": false,
"status": "ACTIVE",
"timestamp": 1580186026417,
}
]
data:done
I did not get any response from the server but in Postman it works fine.
To receive streaming data, you can try adding
request.stream(closure: { data in ... })
Inside closure you should collect data chunks from server and parse them lately, after response is called. In that case response will be nil.
So it would be something like:
let mData = NSMutableData()
self.sessionManager?
.request(url, method: methodType!, parameters: params, encoding: JSONEncoding.default, headers: headers)
.validate()
.stream(closure: { data in mData.append(data) })
.response { response in
//parse mData
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With