본문 바로가기

iOS/Swift

[ios - swift] Alamofire upload image data

//1. pod file에 alamofire 추가
pod 'Alamofire'

//2. pod install
//2-1. intell의 경우
pod install

//2-2. m1의 경우 
arch -x86_64 pod install

 

func postImage(_ imgName: String)
    {
        let url = "https://anyUrl.com"
        
        //Parameter HERE
        let parameters = [
            "version": "1.0.0"
        ]
        
        let image = imageView.image!
        let imgData = image!.jpegData(compressionQuality: 1.0)!
        
        let header : HTTPHeaders = [ ]
//            ["Content-Type" : "multipart/form-data",
//            "token" : GeneralAPI.token ]
        
        AF.upload(multipartFormData: { multipartFormData in
            for (key, value) in parameters {
                multipartFormData.append("\(value)".data(using: .utf8)!, withName: key)
            }
            multipartFormData.append(imgData, withName: "sendImage", fileName: "\(imgName).jpg", mimeType: "image/jpg")
        }, to: url, usingThreshold: UInt64.init(), method: .post, headers: header).response { response in
//            guard let statusCode = response.response?.statusCode,
//                  statusCode == 200
//            else { return }
            switch response.result {
            case .success(let result):
                do {    
                print("success")
                
                let object = try JSONSerialization.jsonObject(with: response.data!, options: []) as? NSDictionary
                guard let jsonObject = object else {return}
                //{
                //	"resultMsg" = "success";
                //}
                if let resultMsg = jsonObject["resultMsg"] as? String {

                    print("result Message :", resultMsg)
                }
                
                }catch let e {
                    print("\(e.localizedDescription)")
                }
            case .failure(let error):
                print(error)
            }
            
            
        }
        
        
    }

'iOS > Swift' 카테고리의 다른 글

[ios - swift] UIView several corner radius  (0) 2022.12.06
[ios - swift] download image from url  (0) 2022.12.05
[ios - swift] resize UIImage  (0) 2022.12.02
[ios - swift] crop UIImage  (0) 2022.11.23
[ios - swift] CMSampleBuffer to UIImage  (0) 2022.11.23