투케이2K

143. (ios/swift) Alamofire ver_5 아라모파이어 http 통신 멀티 파트 사용해 이미지 (image) 파일 업로드 실시 본문

IOS

143. (ios/swift) Alamofire ver_5 아라모파이어 http 통신 멀티 파트 사용해 이미지 (image) 파일 업로드 실시

투케이2K 2022. 4. 4. 18:41
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT

 

[소스 코드]

    // MARK: - [Post 멀티 파트 방식 사진 업로드 요청 실시]
    func mutipartRequest(){
        
        /*
        // -----------------------------------------
        [mutipartRequest 메소드 설명]
        // -----------------------------------------
        1. 사전 spm 매니저 사용해 Alamofire 라이브러리 설치 필요 :
           https://github.com/Alamofire/Alamofire
        // -----------------------------------------
        2. http 허용 info plist : App Transport Security Settings >> Allow Arbitrary Loads >> YES
        // -----------------------------------------
        3. import 추가 : import Alamofire
        // -----------------------------------------
        */
        
        
        // [http 요청 주소 지정]
        let url = "https://app.test.ac.kr/upload_image"
        
        
        // [http 요청 헤더 지정]
        let header : HTTPHeaders = [
            "Content-Type" : "multipart/form-data"
        ]
        
        
        // [http 요청 파라미터 지정 실시]
        let params : Dictionary<String, Any> = [
            "idx" : "12345", // [요청 파라미터]
            "file" : self.imageView.image?.jpegData(compressionQuality: 1) // [UIImageView : 이미지 뷰 사진을 데이터로 만듦]
        ]
        
        
        // [http 요청 수행 실시]
        print("")
        print("====================================")
        print("[\(self.ACTIVITY_NAME) >> mutipartRequest() :: Post 멀티 파트 사진 업로드 요청 실시]")
        print("-------------------------------")
        print("주 소 :: ", url)
        print("-------------------------------")
        print("데이터 :: ", params.description)
        print("====================================")
        print("")
        
        AF.upload(multipartFormData: { multiPart in
            for (key, value) in params {
                if "\(key)" != "file" { // [일반 파라미터 인 경우]
                    if let strData = value as? String {
                        multiPart.append(strData.data(using: .utf8)!, withName: key)
                    }
                    if let intData = value as? Int {
                        multiPart.append("\(intData)".data(using: .utf8)!, withName: key)
                    }
                }
                else { // [이미지 파일 인 경우]
                    let uuidName = UUID().uuidString
                    multiPart.append(value as! Data, withName: "\(key)", fileName: "\(uuidName ?? "").png", mimeType: "image/jpeg")
                }
            }
        }, to: url, method: .post, headers: header)
        .uploadProgress(queue: .main, closure: { progress in
            print("")
            print("====================================")
            print("[\(self.ACTIVITY_NAME) >> mutipartRequest() :: Post 멀티 파트 사진 업로드 상태 확인]")
            print("-------------------------------")
            print("progress :: ", progress.fractionCompleted)
            print("====================================")
            print("")
        })
        .validate(statusCode: 200..<300)
        .responseData { response in
            switch response.result {
            case .success(let res):
                do {
                    print("")
                    print("====================================")
                    print("[\(self.ACTIVITY_NAME) >> mutipartRequest() :: Post 멀티 파트 사진 업로드 응답 확인]")
                    print("-------------------------------")
                    print("응답 코드 :: ", response.response?.statusCode ?? 0)
                    print("-------------------------------")
                    print("응답 데이터 :: ", String(data: res, encoding: .utf8) ?? "")
                    print("====================================")
                    print("")
                    
                    // [비동기 작업 수행]
                    DispatchQueue.main.async {
                        
                    }
                }
                catch (let err){
                    print("")
                    print("====================================")
                    print("[\(self.ACTIVITY_NAME) >> mutipartRequest() :: Post 멀티 파트 사진 업로드 응답 확인]")
                    print("-------------------------------")
                    print("catch :: ", err.localizedDescription)
                    print("====================================")
                    print("")
                }
                break
            case .failure(let err):
                print("")
                print("====================================")
                print("[\(self.ACTIVITY_NAME) >> mutipartRequest() :: Post 멀티 파트 사진 업로드 요청 실패]")
                print("-------------------------------")
                print("응답 코드 :: ", response.response?.statusCode ?? 0)
                print("-------------------------------")
                print("에 러 :: ", err.localizedDescription)
                print("====================================")
                print("")
                break
            }
        }
    }
 

[결과 출력]

 

반응형
Comments