투케이2K

340. (ios/swift5) URLSession 사용해 HTTP 통신 DELETE 요청 수행 실시 본문

IOS

340. (ios/swift5) URLSession 사용해 HTTP 통신 DELETE 요청 수행 실시

투케이2K 2023. 10. 8. 13:05

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT5

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // MARK: - [DELETE 방식 HTTP 통신 수행]
    // -----------------------------------------------------------------------------------------
    func requestDeleteQueryStringHttp(tag: String, url: String, header: Dictionary<String, Any>?, params: Dictionary<String, Any>?, completion: @escaping (Bool, String)->()) {
        
        /*
         // -----------------------------------------
         [requestDeleteQueryStringHttp 메소드 설명]
         // -----------------------------------------
         1. 비동기 DELETE 방식 http 통신 수행 및 리턴 결과 콜백 반환 실시
         // -----------------------------------------
         2. 호출 방법 :
         
         let tag_ = "테스트 json 요청"
         let url_ = "http://jsonplaceholder.typicode.com/posts/1"
         let header_ : Dictionary<String, Any> = [:]
         let params_ : Dictionary<String, Any> = [:]
         
         
         N_AsyncHttp().requestDeleteQueryStringHttp(tag: tag_, url: url_, header: header_, params: params_){(result, response) in
             
             S_Log._D_(description: "HTTP 콜백 결과 확인", data: [response])
             
         }
         // -----------------------------------------
         3. 사전 설정 사항 :
         
         - 필요 info plist 설정
         [1] http 허용 : App Transport Security Settings >> Allow Arbitrary Loads >> YES
         // -----------------------------------------
         */
        
        
        // -----------------------------------------
        // [url 선언 실시]
        // -----------------------------------------
        var urlData = String(describing: url)
        // -----------------------------------------
        
        
        // -----------------------------------------
        // [url 에 파라미터 추가 실시]
        // -----------------------------------------
        if C_Util().dicNotNull(dic_: params) == true {
            
            if urlData.hasSuffix("?") == false {
                urlData += "?"
            }
            
            urlData += C_Util().dicToUrlEncodeQueryString(dic_: params)
            
        }
        
        // -----------------------------------------
        
        
        // -----------------------------------------
        // [URLRequest 생성 실시]
        // -----------------------------------------
        let urlComponents = URLComponents(string: urlData)
        var requestURL = URLRequest(url: (urlComponents?.url)!)
        
        requestURL.httpMethod = "DELETE"
        
        requestURL.addValue("application/x-www-form-urlencoded; charset=utf-8;", 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)")
                
            }

        }
        
        
        S_Log._D_(description: "비동기 DELETE 방식 HTTP [요청] 수행", data: [
            "TAG :: " + String(describing: tag),
            "TYPE :: DELETE >> REQUEST",
            "URL :: " + String(describing: urlData),
            "HEADER :: " + String(describing: header),
            "PARAMS :: " + String(describing: params),
        ])
        
        
        // -----------------------------------------
        // [http 요쳥을 위한 URLSessionDataTask 생성]
        // -----------------------------------------
        let sessionConfig = URLSessionConfiguration.default
        sessionConfig.timeoutIntervalForRequest = N_AsyncHttp.connectTimeout // [커넥션 타임 아웃 설정]
        let session = URLSession(configuration: sessionConfig)
        
        let dataTask = session.dataTask(with: requestURL, completionHandler: { (data, response, error) in

            // [error가 존재하면 종료]
            guard error == nil else {
                S_Log._D_(description: "비동기 DELETE 방식 HTTP [결과] 실패", data: [
                    "TAG :: " + String(describing: tag),
                    "TYPE :: DELETE >> 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._D_(description: "비동기 DELETE 방식 HTTP [결과] 에러", data: [
                    "TAG :: " + String(describing: tag),
                    "TYPE :: DELETE >> 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._D_(description: "비동기 DELETE 방식 HTTP [결과] 확인", data: [
                "TAG :: " + String(describing: tag),
                "TYPE :: DELETE >> 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()
    }
 

[결과 출력]

 

================================================================
LOG :: CLASS PLACE :: N_AsyncHttp.swift :: requestDeleteQueryStringHttp(tag:url:header:params:completion:) :: 1011
-------------------------------------------------
LOG :: NOW TIME :: 2023-10-08 13:00:15
-------------------------------------------------
LOG :: DESCRIPTION :: 비동기 DELETE 방식 HTTP [결과] 확인
-------------------------------------------------
LOG :: TAG :: 테스트 json 요청
-------------------------------------------------
LOG :: TYPE :: DELETE >> RESPONSE
-------------------------------------------------
LOG :: URL :: http://jsonplaceholder.typicode.com/posts/1
-------------------------------------------------
LOG :: HEADER :: Optional([:])
-------------------------------------------------
LOG :: PARAMS :: Optional([:])
-------------------------------------------------
LOG :: STATUS CODE :: 200
-------------------------------------------------
LOG :: RESPONSE DATA :: {}
================================================================

 

반응형
Comments