Notice
Recent Posts
Recent Comments
Link
투케이2K
544. (ios/swift5) [GraphQL] Queries 방식 API 요청 및 응답 확인 수행 본문
[개발 환경 설정]
개발 툴 : XCODE
개발 언어 : SWIFT5
[소스 코드]
// -----------------------------------------------------------------------------------------
// MARK: - [SEARCH FAST] : requestQueriesHttp
// -----------------------------------------------------------------------------------------
func requestQueriesHttp(tag: String, url: String, header: Dictionary<String, Any>?, graphql: String?, completion: @escaping (Bool, String)->()) {
/*
// -----------------------------------------
[requestQueriesHttp 메소드 설명]
// -----------------------------------------
1. 비동기 POST 방식 graphql HTTP 통신 수행 및 콜백 반환 실시
// -----------------------------------------
2. 호출 방법 :
let tag_ = "GraphQL HTTP 요청"
let url_ = "https://graphql.postman-echo.com/graphql"
let header_ : Dictionary<String, Any> = [:]
var graphql_ = ""
graphql_ += "query Hello {\n" +
" hello\n" +
"}"
C_GraphQL_Client_Module().requestQueriesHttp(tag: tag_, url: url_, header: header_, graphql: graphql_){(result, response) in
S_Log._F_(description: "HTTP 콜백 결과 확인", data: [response])
}
// -----------------------------------------
3. 사전 설정 사항 :
- 필요 info plist 설정
[1] http 허용 : App Transport Security Settings >> Allow Arbitrary Loads >> YES
// -----------------------------------------
*/
/*
================================================================
LOG :: TYPE :: FILE :: 🔵
-------------------------------------------------
LOG :: CLASS PLACE :: C_GraphQL_Client_Module.swift :: requestQueriesHttp(tag:url:header:graphql:completion:) :: 269
-------------------------------------------------
LOG :: NOW TIME :: 2024-09-06 19:32:36
-------------------------------------------------
LOG :: DESCRIPTION :: GraphQL Queries Http [결과] 확인
-------------------------------------------------
LOG :: TAG :: GraphQL HTTP 요청
-------------------------------------------------
LOG :: TYPE :: POST >> RESPONSE
-------------------------------------------------
LOG :: URL :: https://graphql.postman-echo.com/graphql
-------------------------------------------------
LOG :: HEADER :: Optional([:])
-------------------------------------------------
LOG :: PARAMS :: ["query": "query Hello {\n hello\n}"]
-------------------------------------------------
LOG :: STATUS CODE :: 200
-------------------------------------------------
LOG :: RESPONSE DATA :: {"data":{"hello":"Hello John Doe"}}
================================================================
// */
// -----------------------------------------
// [사전 방어 로직 체크]
// -----------------------------------------
if url.startsWith(_string: "http") == false {
// [콜백 반환]
completion(false, "[ERROR] :: Url Http Not Start")
return
}
// -----------------------------------------
if String(describing: graphql ?? "").startsWith(_string: "query") == false {
// [콜백 반환]
completion(false, "[ERROR] :: graphql start string error")
return
}
// -----------------------------------------
// -----------------------------------------
// [url 선언 실시]
// -----------------------------------------
let urlData = String(describing: url)
// -----------------------------------------
// -----------------------------------------
// [body json 생성]
// -----------------------------------------
let params : Dictionary<String, Any> = ["query": String(describing: graphql ?? "")]
var jsonData: Data? = nil
if C_Util().dicNotNull(dic_: params) == true {
jsonData = try! JSONSerialization.data(withJSONObject: params, options: [])
}
// -----------------------------------------
// -----------------------------------------
// [URLRequest 생성 실시]
// -----------------------------------------
let urlComponents = URLComponents(string: urlData)
var requestURL = URLRequest(url: (urlComponents?.url)!)
requestURL.httpMethod = "POST"
requestURL.addValue("application/json", forHTTPHeaderField: "Content-Type") // header settings
requestURL.addValue("no-cache", forHTTPHeaderField: "Cache-Control") // header settings
if C_Util().dicNotNull(dic_: header) == true {
for key in header!.keys {
requestURL.addValue("\(String(describing: header![key] ?? ""))", forHTTPHeaderField: "\(key)")
}
}
// [body 데이터 삽입]
if jsonData != nil {
requestURL.httpBody = jsonData // Body 부분에 Json 데이터 삽입 실시
}
S_Log._F_(description: "GraphQL Queries Http [요청] 수행", data: [
"TAG :: " + String(describing: tag),
"TYPE :: POST >> REQUEST",
"URL :: " + String(describing: urlData),
"HEADER :: " + String(describing: header),
"PARAMS :: " + String(describing: params),
])
// -----------------------------------------
// [http 요쳥을 위한 URLSessionDataTask 생성]
// -----------------------------------------
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = C_GraphQL_Client_Module.TIME_OUT // [커넥션 타임 아웃 설정]
sessionConfig.timeoutIntervalForResource = C_GraphQL_Client_Module.TIME_OUT // [리소스 읽기 , 쓰기]
let session = URLSession(configuration: sessionConfig)
S_FileManager.appHttpLogSave(description: String(describing: tag), request: requestURL, data: nil, response: nil, error: nil)
let dataTask = session.dataTask(with: requestURL, completionHandler: { (data, response, error) in
S_FileManager.appHttpLogSave(description: nil, request: nil, data: data, response: response as? HTTPURLResponse, error: error)
// [error가 존재하면 종료]
guard error == nil else {
S_Log._F_(description: "GraphQL Queries Http [결과] 실패", data: [
"TAG :: " + String(describing: tag),
"TYPE :: POST >> FAIL",
"URL :: " + String(describing: urlData),
"HEADER :: " + String(describing: header),
"PARAMS :: " + String(describing: params),
"ERROR :: \(error?.localizedDescription ?? "")"
])
// [콜백 반환]
completion(false, "[ERROR] :: \(error?.localizedDescription ?? "")")
return
}
// [status 코드 체크 실시]
let successsRange = 200..<300
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, successsRange.contains(statusCode)
else {
S_Log._F_(description: "GraphQL Queries Http [결과] 에러", data: [
"TAG :: " + String(describing: tag),
"TYPE :: POST >> ERROR",
"URL :: " + String(describing: urlData),
"HEADER :: " + String(describing: header),
"PARAMS :: " + String(describing: params),
"STATUS CODE :: " + String(describing: (response as? HTTPURLResponse)?.statusCode ?? 0),
"RESPONSE DATA :: \((response as? HTTPURLResponse)?.description ?? "")"
])
// [콜백 반환]
completion(false, "[ERROR] :: \((response as? HTTPURLResponse)?.description ?? "")")
return
}
// [response 데이터 획득]
let resultCode = (response as? HTTPURLResponse)?.statusCode ?? 0 // [상태 코드]
let resultData = String(data: data!, encoding: .utf8) ?? "" // [데이터 확인]
S_Log._F_(description: "GraphQL Queries Http [결과] 확인", data: [
"TAG :: " + String(describing: tag),
"TYPE :: POST >> RESPONSE",
"URL :: " + String(describing: urlData),
"HEADER :: " + String(describing: header),
"PARAMS :: " + String(describing: params),
"STATUS CODE :: " + String(describing: resultCode),
"RESPONSE DATA :: " + String(describing: resultData)
])
// [콜백 반환]
completion(true, resultData)
})
// [network 통신 실행]
dataTask.resume()
}
[결과 출력]
반응형
'IOS' 카테고리의 다른 글
Comments