Hi,
I am constantly getting the same error when trying to call the OpenAI API. I am using Swift (iOS) and whatever I do, every API all is getting the following error: The network connection was lost.
I checked my OpenAI Account if there is something wrong - but everything works well both from curl and jscript - i can access the API without any issues and it returns correct responses.
My code is:
let url = URL(string: “removed”)!
var request = URLRequest(url: url)
request.httpMethod = “POST”
request.setValue(“application/json”, forHTTPHeaderField: “Content-Type”)
request.setValue(“Bearer API_KEY_REMOVED”, forHTTPHeaderField: “Authorization”)
let requestBody: [String: Any] = [
"model": "gpt-4o",
"messages": [
[
"role": "user",
"content": [
[
"type": "text",
"text": "Write a haiku about weightlifting"
]
]
]
],
"temperature": 1,
"max_tokens": 100,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"response_format": [
"type": "text"
]
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
let (responseData, response) = try await URLSession.shared.data(for: request)
print(response)
print(responseData)
//print("-----> responseData \n \(String(data: responseData, encoding: .utf8) as AnyObject) \n")
}
catch { print(error) }
And this is the complete error message:
Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.” UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x600000c40210 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 “(null)” UserInfo={NSErrorPeerAddressKey=<CFData 0x600002104870 [0x1e6ebb4f0]>{length = 16, capacity = 16, bytes = 0x100201bbac4200f30000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
“LocalDataTask .<1>”
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=removed, NSErrorFailingURLKey=removed, _kCFStreamErrorDomainKey=4}
Anyone ideas?
Thanks,
Mario