URLSession.shared.dataTask return zero bytes
My goal is to call a http service that returns a json to be parsed as an array of NewsModel objects.
I defined a struct like that
struct NewsModel: Decodable {
var id: Int
var title: String
var content: String
}
and wrote this method in Service.swift class:
func getNews(pageSize: Int, pageCount: Int, completion: @escaping ([NewsModel]?) -> ()) {
guard let url = URL(string: "(Service.baseURLSSMService)/news?pageSize=(pageSize)&pageCount=(pageCount)") else {return}
var retVal = [NewsModel]()
// Create URLRequest
var request = URLRequest(url: url)
// Set headers and http method
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
completion(nil)
return }
do{
print("RESPONSE:(response.debugDescription)")
retVal = try
JSONDecoder().decode([NewsModel].self, from: dataResponse)
completion(retVal)
} catch let parsingError {
print("Error", parsingError)
completion(nil)
}
}
task.resume()
}
I need to call this method from my HomeViewController. I used this code in my viewDidLoad:
Service.sharedInstance.getNews(pageSize: 10, pageCount: 1) { (news) in
// I need the first element of the news array
// I save it into a global variable
self.homeNews = news?.first
DispatchQueue.main.async {
if self.homeNews != nil {
self.myLabel.text = self.homeNews?.title
}
else {
self.myLabel.text = "No data received."
}
}
}
When I run the code, it always happens that the getNews function returns 0 bytes so nothing can be parsed by the JSONDecoder. This is the error message:
Error dataCorrupted(Swift.DecodingError.Context(codingPath: ,
debugDescription: "The given data was not valid JSON.",
underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840
"No value." UserInfo={NSDebugDescription=No value.})))
If I call it twice the last time proper values are received. What am I doing wrong? Because I guess I'm doing wrong something but I cannot get it.
EDIT 1:
This is a json sample:
[
{
"id": 2048,
"title": "title-sample-1",
"content": "content-sample-1"
},
{
"id": 2047,
"title": "title-sample-2",
"content": "content-sample-2"
}
]
EDIT 2:
Here is the response.debugDescription
RESPONSE:Optional(<NSHTTPURLResponse: 0x2830a1160> { URL: http://.../news?pageSize=1&pageCount=1 } { Status Code: 400, Headers {
Connection = (
close
);
Date = (
"Tue, 27 Nov 2018 15:38:38 GMT"
);
"Transfer-Encoding" = (
Identity
); } })
json swift urlsession nsurlsessiondatatask
|
show 11 more comments
My goal is to call a http service that returns a json to be parsed as an array of NewsModel objects.
I defined a struct like that
struct NewsModel: Decodable {
var id: Int
var title: String
var content: String
}
and wrote this method in Service.swift class:
func getNews(pageSize: Int, pageCount: Int, completion: @escaping ([NewsModel]?) -> ()) {
guard let url = URL(string: "(Service.baseURLSSMService)/news?pageSize=(pageSize)&pageCount=(pageCount)") else {return}
var retVal = [NewsModel]()
// Create URLRequest
var request = URLRequest(url: url)
// Set headers and http method
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
completion(nil)
return }
do{
print("RESPONSE:(response.debugDescription)")
retVal = try
JSONDecoder().decode([NewsModel].self, from: dataResponse)
completion(retVal)
} catch let parsingError {
print("Error", parsingError)
completion(nil)
}
}
task.resume()
}
I need to call this method from my HomeViewController. I used this code in my viewDidLoad:
Service.sharedInstance.getNews(pageSize: 10, pageCount: 1) { (news) in
// I need the first element of the news array
// I save it into a global variable
self.homeNews = news?.first
DispatchQueue.main.async {
if self.homeNews != nil {
self.myLabel.text = self.homeNews?.title
}
else {
self.myLabel.text = "No data received."
}
}
}
When I run the code, it always happens that the getNews function returns 0 bytes so nothing can be parsed by the JSONDecoder. This is the error message:
Error dataCorrupted(Swift.DecodingError.Context(codingPath: ,
debugDescription: "The given data was not valid JSON.",
underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840
"No value." UserInfo={NSDebugDescription=No value.})))
If I call it twice the last time proper values are received. What am I doing wrong? Because I guess I'm doing wrong something but I cannot get it.
EDIT 1:
This is a json sample:
[
{
"id": 2048,
"title": "title-sample-1",
"content": "content-sample-1"
},
{
"id": 2047,
"title": "title-sample-2",
"content": "content-sample-2"
}
]
EDIT 2:
Here is the response.debugDescription
RESPONSE:Optional(<NSHTTPURLResponse: 0x2830a1160> { URL: http://.../news?pageSize=1&pageCount=1 } { Status Code: 400, Headers {
Connection = (
close
);
Date = (
"Tue, 27 Nov 2018 15:38:38 GMT"
);
"Transfer-Encoding" = (
Identity
); } })
json swift urlsession nsurlsessiondatatask
It looks like your JSON doesn't match with your struct. Can you add your JSON please?
– Robert Dresler
Nov 27 '18 at 15:13
Have you tested your url in a web browser?
– Joakim Danielson
Nov 27 '18 at 15:13
Alsocompletion(retVal)needs to be within your do catch block
– Scriptable
Nov 27 '18 at 15:14
@RobertDresler I added a json sample in the EDIT 1 block. But I wonder why the second time the call works if the json doesn't not match my struct...
– cicaletto79
Nov 27 '18 at 15:22
add acompletion(nil)afterprint("Error", parsingError)andcompletion(retVal)afterretVal = try ...and removeDispatchQueue.main.async { completion(retVal) }
– Leo Dabus
Nov 27 '18 at 15:23
|
show 11 more comments
My goal is to call a http service that returns a json to be parsed as an array of NewsModel objects.
I defined a struct like that
struct NewsModel: Decodable {
var id: Int
var title: String
var content: String
}
and wrote this method in Service.swift class:
func getNews(pageSize: Int, pageCount: Int, completion: @escaping ([NewsModel]?) -> ()) {
guard let url = URL(string: "(Service.baseURLSSMService)/news?pageSize=(pageSize)&pageCount=(pageCount)") else {return}
var retVal = [NewsModel]()
// Create URLRequest
var request = URLRequest(url: url)
// Set headers and http method
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
completion(nil)
return }
do{
print("RESPONSE:(response.debugDescription)")
retVal = try
JSONDecoder().decode([NewsModel].self, from: dataResponse)
completion(retVal)
} catch let parsingError {
print("Error", parsingError)
completion(nil)
}
}
task.resume()
}
I need to call this method from my HomeViewController. I used this code in my viewDidLoad:
Service.sharedInstance.getNews(pageSize: 10, pageCount: 1) { (news) in
// I need the first element of the news array
// I save it into a global variable
self.homeNews = news?.first
DispatchQueue.main.async {
if self.homeNews != nil {
self.myLabel.text = self.homeNews?.title
}
else {
self.myLabel.text = "No data received."
}
}
}
When I run the code, it always happens that the getNews function returns 0 bytes so nothing can be parsed by the JSONDecoder. This is the error message:
Error dataCorrupted(Swift.DecodingError.Context(codingPath: ,
debugDescription: "The given data was not valid JSON.",
underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840
"No value." UserInfo={NSDebugDescription=No value.})))
If I call it twice the last time proper values are received. What am I doing wrong? Because I guess I'm doing wrong something but I cannot get it.
EDIT 1:
This is a json sample:
[
{
"id": 2048,
"title": "title-sample-1",
"content": "content-sample-1"
},
{
"id": 2047,
"title": "title-sample-2",
"content": "content-sample-2"
}
]
EDIT 2:
Here is the response.debugDescription
RESPONSE:Optional(<NSHTTPURLResponse: 0x2830a1160> { URL: http://.../news?pageSize=1&pageCount=1 } { Status Code: 400, Headers {
Connection = (
close
);
Date = (
"Tue, 27 Nov 2018 15:38:38 GMT"
);
"Transfer-Encoding" = (
Identity
); } })
json swift urlsession nsurlsessiondatatask
My goal is to call a http service that returns a json to be parsed as an array of NewsModel objects.
I defined a struct like that
struct NewsModel: Decodable {
var id: Int
var title: String
var content: String
}
and wrote this method in Service.swift class:
func getNews(pageSize: Int, pageCount: Int, completion: @escaping ([NewsModel]?) -> ()) {
guard let url = URL(string: "(Service.baseURLSSMService)/news?pageSize=(pageSize)&pageCount=(pageCount)") else {return}
var retVal = [NewsModel]()
// Create URLRequest
var request = URLRequest(url: url)
// Set headers and http method
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
completion(nil)
return }
do{
print("RESPONSE:(response.debugDescription)")
retVal = try
JSONDecoder().decode([NewsModel].self, from: dataResponse)
completion(retVal)
} catch let parsingError {
print("Error", parsingError)
completion(nil)
}
}
task.resume()
}
I need to call this method from my HomeViewController. I used this code in my viewDidLoad:
Service.sharedInstance.getNews(pageSize: 10, pageCount: 1) { (news) in
// I need the first element of the news array
// I save it into a global variable
self.homeNews = news?.first
DispatchQueue.main.async {
if self.homeNews != nil {
self.myLabel.text = self.homeNews?.title
}
else {
self.myLabel.text = "No data received."
}
}
}
When I run the code, it always happens that the getNews function returns 0 bytes so nothing can be parsed by the JSONDecoder. This is the error message:
Error dataCorrupted(Swift.DecodingError.Context(codingPath: ,
debugDescription: "The given data was not valid JSON.",
underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840
"No value." UserInfo={NSDebugDescription=No value.})))
If I call it twice the last time proper values are received. What am I doing wrong? Because I guess I'm doing wrong something but I cannot get it.
EDIT 1:
This is a json sample:
[
{
"id": 2048,
"title": "title-sample-1",
"content": "content-sample-1"
},
{
"id": 2047,
"title": "title-sample-2",
"content": "content-sample-2"
}
]
EDIT 2:
Here is the response.debugDescription
RESPONSE:Optional(<NSHTTPURLResponse: 0x2830a1160> { URL: http://.../news?pageSize=1&pageCount=1 } { Status Code: 400, Headers {
Connection = (
close
);
Date = (
"Tue, 27 Nov 2018 15:38:38 GMT"
);
"Transfer-Encoding" = (
Identity
); } })
json swift urlsession nsurlsessiondatatask
json swift urlsession nsurlsessiondatatask
edited Nov 27 '18 at 15:42
cicaletto79
asked Nov 27 '18 at 15:09
cicaletto79cicaletto79
979
979
It looks like your JSON doesn't match with your struct. Can you add your JSON please?
– Robert Dresler
Nov 27 '18 at 15:13
Have you tested your url in a web browser?
– Joakim Danielson
Nov 27 '18 at 15:13
Alsocompletion(retVal)needs to be within your do catch block
– Scriptable
Nov 27 '18 at 15:14
@RobertDresler I added a json sample in the EDIT 1 block. But I wonder why the second time the call works if the json doesn't not match my struct...
– cicaletto79
Nov 27 '18 at 15:22
add acompletion(nil)afterprint("Error", parsingError)andcompletion(retVal)afterretVal = try ...and removeDispatchQueue.main.async { completion(retVal) }
– Leo Dabus
Nov 27 '18 at 15:23
|
show 11 more comments
It looks like your JSON doesn't match with your struct. Can you add your JSON please?
– Robert Dresler
Nov 27 '18 at 15:13
Have you tested your url in a web browser?
– Joakim Danielson
Nov 27 '18 at 15:13
Alsocompletion(retVal)needs to be within your do catch block
– Scriptable
Nov 27 '18 at 15:14
@RobertDresler I added a json sample in the EDIT 1 block. But I wonder why the second time the call works if the json doesn't not match my struct...
– cicaletto79
Nov 27 '18 at 15:22
add acompletion(nil)afterprint("Error", parsingError)andcompletion(retVal)afterretVal = try ...and removeDispatchQueue.main.async { completion(retVal) }
– Leo Dabus
Nov 27 '18 at 15:23
It looks like your JSON doesn't match with your struct. Can you add your JSON please?
– Robert Dresler
Nov 27 '18 at 15:13
It looks like your JSON doesn't match with your struct. Can you add your JSON please?
– Robert Dresler
Nov 27 '18 at 15:13
Have you tested your url in a web browser?
– Joakim Danielson
Nov 27 '18 at 15:13
Have you tested your url in a web browser?
– Joakim Danielson
Nov 27 '18 at 15:13
Also
completion(retVal) needs to be within your do catch block– Scriptable
Nov 27 '18 at 15:14
Also
completion(retVal) needs to be within your do catch block– Scriptable
Nov 27 '18 at 15:14
@RobertDresler I added a json sample in the EDIT 1 block. But I wonder why the second time the call works if the json doesn't not match my struct...
– cicaletto79
Nov 27 '18 at 15:22
@RobertDresler I added a json sample in the EDIT 1 block. But I wonder why the second time the call works if the json doesn't not match my struct...
– cicaletto79
Nov 27 '18 at 15:22
add a
completion(nil) after print("Error", parsingError) and completion(retVal) after retVal = try ... and remove DispatchQueue.main.async { completion(retVal) }– Leo Dabus
Nov 27 '18 at 15:23
add a
completion(nil) after print("Error", parsingError) and completion(retVal) after retVal = try ... and remove DispatchQueue.main.async { completion(retVal) }– Leo Dabus
Nov 27 '18 at 15:23
|
show 11 more comments
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53502582%2furlsession-shared-datatask-return-zero-bytes%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53502582%2furlsession-shared-datatask-return-zero-bytes%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
It looks like your JSON doesn't match with your struct. Can you add your JSON please?
– Robert Dresler
Nov 27 '18 at 15:13
Have you tested your url in a web browser?
– Joakim Danielson
Nov 27 '18 at 15:13
Also
completion(retVal)needs to be within your do catch block– Scriptable
Nov 27 '18 at 15:14
@RobertDresler I added a json sample in the EDIT 1 block. But I wonder why the second time the call works if the json doesn't not match my struct...
– cicaletto79
Nov 27 '18 at 15:22
add a
completion(nil)afterprint("Error", parsingError)andcompletion(retVal)afterretVal = try ...and removeDispatchQueue.main.async { completion(retVal) }– Leo Dabus
Nov 27 '18 at 15:23