无法在swift中通过URLSession进行订阅?

ua4mk5z4  于 2023-04-28  发布在  Swift
关注(0)|答案(1)|浏览(133)

我尝试使用URLSessionWundergraph服务器获取订阅数据,通过开启httpShouldUsePipelining进行网络请求和响应处理。这是我的代码

class SubscriptionNetworkManager{
    
    private var request: URLRequest!
    
    public init(_ url: String,
                withURLParameter jsonObject: [String: Any]) {
        
        guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: []),
              let jsonString = String(data: jsonData, encoding: .utf8),
              var urlComponents = URLComponents(string: url)
        else {
            return
        }
        
        urlComponents.queryItems = [URLQueryItem(name: "wg_variables", value: jsonString)]
        
        if let finalUrl = urlComponents.url {
            self.request = URLRequest(url: finalUrl)
            print(finalUrl )
        }
        
        self.request.httpMethod = HttpMethod.get.rawValue
        self.request.httpShouldUsePipelining = true
        
        if let accessToken = UserDefaults.accessToken {
            
            let tempHeader = [
                "Authorization": "Bearer \(accessToken)"
            ]
            
            self.request.allHTTPHeaderFields = tempHeader
            
            let encoder = JSONEncoder()
            if let jsonData = try? encoder.encode(tempHeader) {
                let jsonString = String(data: jsonData, encoding: .utf8) ?? ""
                print("headers:-> ", jsonString)
            }
        } else {
            fatalError("No Header!!!")
        }
    }
    
    // Fetch data from specified url
    func fetchData<T: Codable>(withCompletion completion: @escaping (T) -> Void,
                               withCompletionWithError errors: @escaping (String) -> Void) {
        
        URLSession.shared.dataTask(with: self.request) { (data, response, error) in
            DispatchQueue.main.async {
                
                if let error = error {
                    let errorMessage = error.localizedDescription
                    errors(errorMessage)
                    return
                }
                
                guard let data = data else {
                    let errorMessage = error?.localizedDescription ?? "Failed to fetch courses"
                    errors(errorMessage)
                    return
                }
                
                self.printOutResponse(data: data, response: response)
                
                do {
                    let decodedData = try JSONDecoder().decode(T.self, from: data)
                    completion(decodedData)
                } catch {
                    errors("Error decoding data: \(error)")
                }
            }
        }.resume()
    }
    
    // MARK: Print Response from API
    private func printOutResponse(data: Data, response: URLResponse?) {
        // for printing response
        do {
            
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            print(json)
        } catch {
            print(error)
        }
        
        guard let httpResponse = response as? HTTPURLResponse else { return }
        let statusCode = httpResponse.statusCode
        print("Status Code =>", statusCode)
    }
}

我打过电话

let url = Urls.baseUrl + "protected/SubscribeToConversationsByChannelId"
let object = ["channel_id": "d111350f-80cb-4fab-beaa-84c090717d2f"]
    SubscriptionNetworkManager.init(url,
                                    withURLParameter: object).fetchData() { (response: ProtectedSubscribeToConversationsByChannelIdResponseDataHasuraMochiConversations) in
        print(response)
    } withCompletionWithError: { error in
        print(error)
    }

我反复得到超时错误,这里是详细错误

Task <D5C6F257-DEF4-491C-89C4-77425227490A>.<4> finished with error [-1001] Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSUnderlyingError=0x2824b8c90 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <D5C6F257-DEF4-491C-89C4-77425227490A>.<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <D5C6F257-DEF4-491C-89C4-77425227490A>.<4>"
), NSLocalizedDescription=The request timed out.,

但是当我尝试使用Postman时,通过提供相同的params,和header,我得到状态码200。这是我的 Postman 截图。

然后在postman的代码段下找到cURL,将cURL粘贴到终端,更新服务器后,在终端可以看到真实的数据。目前,我们使用的是WunderGraph服务器。我试了很多次,但还是无法解决。有人能帮我解决这个问题吗?

xqkwcwgp

xqkwcwgp1#

根据评论中的讨论发布答案:
代码Urls.baseUrl + "protected/SubscribeToConversationsByChannelId"出现问题,其中在将路径组件添加到基URL时缺少/
解决方案:

Urls.baseUrl + "/protected/SubscribeToConversationsByChannelId"

相关问题