如何使用 JSON 格式 iOS swift4 中的参数在 byteArray 中发送图像

how to send image in byteArray with parameters in JSON format iOS swift4

我是 iOS 的初学者,我对编程的了解很少。现在,在我的项目中,我遇到了一项任务,我必须发送正在创建的用户的数据以及为相机或照片库上传的图像。实际上我不知道该怎么做,我在互联网、Whosebug 和其他一些博客上搜索了如何在 swift4 中发送带参数的图像,并试图了解这个过程,我已经尝试了一个星期,我不知道不知道还能做什么。我在这里发布我的代码:

 @IBAction func createAccountTapped(_sender: UIButton!) {

        guard let image = profileImgView.image else {return}

        let imageData = UIImageJPEGRepresentation(image, 0.7)
        print(imageData!)

        let byteArray = Array(imageData!)

        let updateProfileUrl = "http://isit.beetlerim.com/api/UsersAPI/UpdateUserProfile"

        let parameters = [
            "UserName":userNameTF.text!,
            "Password":passwordTF.text!,
            "UserTypeId":2,
            "profilePic":"\(arc4random()).jpg",
            "profileImage":byteArray,
            "DOB":dateOfBirthTF.text!,
            "PhoneNumber":phoneNumberTF.text!,
            "Mobile":phoneNumberTF.text!,
            "Email":emailAddressTF.text!,
            "AddressLine1":address1TF.text!,
            "AddressLine2":address2TF.text!,
            "City":cityTF.text!,
            "State":stateTF.text!,
            "Country":countryTF.text!,
            "ZipCode":zipcodeTF.text!
            ] as [String : Any]

        let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

        print(jsonData!)

        // create post request
        let url = URL(string: updateProfileUrl)!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        // insert json data to the request
        request.httpBody = jsonData
        request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accpet")
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: .allowFragments )
            if let responseJSON = responseJSON as? [String: Any] {
                print(responseJSON)
            }
        }

        task.resume()
    }

我收到 responseJSON:["message":发生错误。] }

我也试过很多其他方法.. none 都没有用.. 请帮帮我:

首先,您需要确保图像大小小于服务器端的最大值,这是服务器可能会告诉您的一种方式,但您仍然需要在服务器端进行调试。假设大多数情况下它通常被限制为最大 2 MB。

因此您需要先调整它的大小,然后将其转换为 base64,但这不是上传图片的首选方式,因为它会使传输的数据大小增加 33%。服务器端应该使用 multipart/form-data 因为它是通过 HTTP 传输二进制数据的标准方式。但是给你:

let imageResized = image.resizeWith(percentage: 0.1)
let base64 = imageResized?.toBase64()

您需要使用以下扩展程序:

extension UIImage {
    func resizeWith(percentage: CGFloat) -> UIImage? {
        let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage)))
        imageView.contentMode = .scaleAspectFit
        imageView.image = self
        UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        imageView.layer.render(in: context)
        guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        UIGraphicsEndImageContext()
        return result
    }
}

extension UIImage {
    
    func toBase64() -> String? {
        
        let imageData : NSData = UIImageJPEGRepresentation(self, 1.0)! as NSData
        return imageData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters)
    }
}

最后以这种方式发送您的参数:

let parameters = [
            "UserName":userNameTF.text!,
            "Password":passwordTF.text!,
            "UserTypeId":2,
            "profilePic":"\(arc4random()).png",
            "profileImage":base64!,
            "DOB":dateOfBirthTF.text!,
            "PhoneNumber":phoneNumberTF.text!,
            "Mobile":phoneNumberTF.text!,
            "Email":emailAddressTF.text!,
            "AddressLine1":address1TF.text!,
            "AddressLine2":address2TF.text!,
            "City":cityTF.text!,
            "State":stateTF.text!,
            "Country":countryTF.text!,
            "ZipCode":zipcodeTF.text!
            ] as [String : Any]

希望这有效!