본문 바로가기
iOS

[Alamofire_5] 이미지 업로드 예제 코드

by HaningYa 2020. 8. 28.
728x90

 

개발하는 앱에서 이미지 업로드가 있었다.

Alamofire 4로 구현해봤는데 Alamofire 5 에서 많이 달라진것 같다.

메모해놔야겠다.

Alamofire 4 코드

func updateProfileImage(_ image : UIImage){
        let parameters: Parameters = [
            "token" : UserDefaults.standard.string(forKey: "userToken") ?? "",
            "uuid" : UIDevice.current.identifierForVendor?.uuidString.lowercased() ?? ""
        ]
        let imageData = image.jpegData(compressionQuality: 1)!
        // Start Alamofire
        Alamofire.upload(multipartFormData: { multipartFormData in
            for (key,value) in parameters {
                multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
            }
            multipartFormData.append(imageData, withName: "profile_image", fileName: "profile_image.jpg",mimeType: "image/jpeg")
        }
            ,usingThreshold: UInt64.init()
            ,to: "\(Network.baseURL)/api/user/update/profile_image"
            ,method: .post
            ,encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        switch response.result{
                        case .success(_):
                            do{
                                let res = try JSONDecoder().decode(Response.self, from : response.data!)
                                if res.code == "S01" {
                                    DispatchQueue.main.async {
                                        Utils.showAlertMessage(vc: self, titleStr: "성공", messageStr:  "프로필 사진이 변경되었습니다.")
                                    }
                                    self.getUserInfo()
                                }else{
                                    Utils.showAlertMessage(vc: self, titleStr: "실패", messageStr: res.message ?? "메시지")
                                }
                            }catch{
                                print(error)
                            }
                            break
                        case .failure(let error):
                            print(error)
                            print(response.data!)
                            break
                        }
                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
        })
        
    }

Alamfire 5 코드

 private func updateProfileImage(_ image : UIImage){
        
        if selectedTag.count == 0 {
            self.alert(title: "하나 이상의 태그를 선택해 주세요.")
            return
        }
        var str = "{ \"value\" : ["
        for i in 0..<selectedTag.count {
            if i == selectedTag.count-1 {
                str.append("\(selectedTag[i])] }")
                break
            }
            str.append("\(selectedTag[i]),")
        }
        
        
        let parameters : Parameters = [
            "newsletter_name": tfTitle.text ?? "",
            "newsletter_explain" : tfExplain.text ?? "",
            "newsletter_tags" : str,
            "register_url" : tfURL.text ?? ""
        ]
        
        let imageData = image.jpegData(compressionQuality: 1)!
        let url = "\(ApiService.baseURL)/newsletters/post/"
        
        upload(image: imageData, to: url, params: parameters)
        
    }//end of function
    func upload(image: Data, to url: String, params: [String: Any]) {
        
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data"
        ]
        AF.upload(multipartFormData: { multiPart in
            for (key, value) in params {
                if let temp = value as? String {
                    multiPart.append(temp.data(using: .utf8)!, withName: key)
                }
                if let temp = value as? Int {
                    multiPart.append("\(temp)".data(using: .utf8)!, withName: key)
                }
                if let temp = value as? NSArray {
                    temp.forEach({ element in
                        let keyObj = key + "[]"
                        if let string = element as? String {
                            multiPart.append(string.data(using: .utf8)!, withName: keyObj)
                        } else
                            if let num = element as? Int {
                                let value = "\(num)"
                                multiPart.append(value.data(using: .utf8)!, withName: keyObj)
                        }
                    })
                }
            }
            multiPart.append(image, withName: "newsletter_image", fileName: "\(self.tfTitle.text ?? "")_logo.png", mimeType: "image/jpeg")
        }, to: url
         , headers: headers)
            .uploadProgress(queue: .main, closure: { progress in
                //Current upload progress of file
                print("Upload Progress: \(progress.fractionCompleted)")
            })
            .responseJSON(completionHandler: { data in
                switch data.result{
                case .success(_):
                    do {
                        let res = try JSONDecoder().decode(StringResponse.self, from : data.data!)
                        if res.status == "S00" {
                            DispatchQueue.main.async {
                                self.alert(title: "등록성공", message: "뉴스레터 등록에 성공했습니다.", okTitle: "확인", okHandler: nil, cancelTitle: "확인", cancelHandler: { (action) in
                                    
                                    self.dismiss(animated: true, completion: nil)
                                }, completion: nil)
                            }
                        }else{
                            Utils.showAlertMessage(vc: self, titleStr: "등록오류", messageStr: res.message)
                            print(res.message)
                        }
                    }catch{
                        
                        print(data.description)
                        print("error")
                    }
                    
                case .failure(let error):
                    
                    print(error.errorDescription ?? "error")
                }
                //Do what ever you want to do with response
            })
    }

 

 

 

728x90

댓글