无法在iOS上的Swift中将base64字符串发送到服务器

问题描述 投票:0回答:1

在我的应用程序中,我已使用UIImagePickerController从照片中选择图像,然后进行压缩并转换为base64 string。最后,我将base64字符串上传到服务器。在这里,服务器不接受base64 string并且不能正常工作,但是在Android和Postman中,它可以正常工作。我在代码中找不到错误。

这里我提到UIImagePickerControllerDelegate:

// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    selectedImage = selectedImage.resizeWithWidth(width: 700)!
    picker.dismiss(animated: true, completion: nil)
    DispatchQueue.main.async {
        self.collPhotos.reloadData()
    }
}

这里我提到了Base64转换并将参数字符串发布到服务器:

func addImagesApiCAll() {
    let imagedata1:UIImage = selectedImage as! UIImage
    let compressData = UIImagePNGRepresentation(imagedata1)
    let base64 = compressData?.base64EncodedString(options: .lineLength64Characters)
    print("charCount",base64!.count)

    if Reachability()!.isReachable {
        let id = Singleton.sharedInstance.selectedCategory!
        let parameterStr = "property_id=\(self.PropertyID)&photos=\(base64!)&lang_code=\(lanuguage_selection.value(forKey: "language") ?? "en")&base_id=\(id)&user_id=\(login_session.value(forKey: "UserId")!)"
        Network.shared.POSTRequest(withParameterString: parameterStr, serviceURL: SAVE_PHOTO_LISTING, APIKEY: "SAVE_PHOTO_LISTING")
    } else {
        showInformation(title: "Network Error", message: "Please check your internet connection")
    }
}

extension AddPhotoViewController: HTTP_POST_STRING_REQUEST_PROTOCOL {
func httpPostRequest(APIKEY: String, requestURL: String, responseDict: NSDictionary, errorDict: String) {
    ListingActivityDelegate.hideActivity()
    if APIKEY == "SAVE_PHOTO_LISTING"{
       if errorDict.count == 0 {
        print(responseDict)
        let mod = RentYourSpaceModel(fromDictionary: responseDict as! [String : Any])
        if mod.status! != 0 {
           Singleton.sharedInstance.rentYourSpace = mod
            if Singleton.sharedInstance.rentYourSpace.result[0].step5.productImage.count == 0{
                imageFromResponse = "NO"
            } else {
                imageFromResponse  = "YES"
            }
        }
        self.showInformation(title: "Application", message: mod.message)
    }
       else {

  }
}
}
}

这里我提到从相机或图库中选择图像的代码:

@IBAction func act_AddPhoto(_ sender: UIButton) {
    let actionSheet = UIAlertController(title: "Home Stay", message: "Choose Image", preferredStyle: .actionSheet)
    actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
        self.openCamera()
    }))
    actionSheet.addAction(UIAlertAction(title: "Photos", style: .default, handler: { _ in
        self.openGallary()
    }))
    actionSheet.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
    //If you want work actionsheet on ipad then you have to use popoverPresentationController to present the actionsheet, otherwise app will crash in iPad
    switch UIDevice.current.userInterfaceIdiom {
    case .pad:
        actionSheet.popoverPresentationController?.sourceView = sender
        actionSheet.popoverPresentationController?.sourceRect = sender.bounds
        actionSheet.popoverPresentationController?.permittedArrowDirections = .up
    default:
        break
    }
    self.present(actionSheet, animated: true, completion: nil)
}

//MARK: - Open the camera
func openCamera() {
    if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)){
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        //If you dont want to edit the photo then you can set allowsEditing to false
        imagePicker.allowsEditing = true
        imagePicker.delegate = self
        self.present(imagePicker, animated: true, completion: nil)
    }
    else{
        let alert  = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

//MARK: - Choose image from camera roll
func openGallary(){
    imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
    //If you dont want to edit the photo then you can set allowsEditing to false
    imagePicker.allowsEditing = true
    imagePicker.delegate = self
    self.present(imagePicker, animated: true, completion: nil)
}

这里提供POSTRequest方法:

//MARK:- Post request with parameter String.
func POSTRequest(withParameterString: String , serviceURL: String , APIKEY: String)
{
    var RESPONSE_ERROR = String()
    var RESPONSE_DATA = NSDictionary()
    let Url = String(format: serviceURL)
    guard let serviceUrl = URL(string: Url) else { return }
    var request = URLRequest(url: serviceUrl)
    let postString = withParameterString
 //   print(postString)
    request.httpBody = postString.data(using: String.Encoding.utf8);
  //request.addValue("application/json", forHTTPHeaderField: "content-type")
    request.httpMethod = "POST"
    let task = URLSession.shared.dataTask(with: request, completionHandler: {
        data, response, error in
        if let response = response {
            print(response)
        }
        if let resdata = data {
            do {

              //  print(response)

                let json =  try JSONSerialization.jsonObject(with: resdata, options: .mutableContainers) as? NSDictionary

                   if let parseJSON = json {

                      //print(json)
                    if parseJSON.object(forKey: "status") as! NSInteger == 1 {
                        if error != nil {
                           RESPONSE_ERROR = (error?.localizedDescription)!
                        }
                        DispatchQueue.main.async {
                            RESPONSE_DATA = parseJSON
                            self.HTTP_POST_STRING_REQUEST_DELEGATE?.httpPostRequest(APIKEY: APIKEY, requestURL: serviceURL, responseDict: RESPONSE_DATA, errorDict: RESPONSE_ERROR)
                        }
                    } else {
                        DispatchQueue.main.async {
                             RESPONSE_DATA = parseJSON
                            self.HTTP_POST_STRING_REQUEST_DELEGATE?.httpPostRequest(APIKEY: APIKEY, requestURL: serviceURL, responseDict: RESPONSE_DATA, errorDict: RESPONSE_ERROR)
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        RESPONSE_ERROR = "No Data"
                        self.HTTP_POST_STRING_REQUEST_DELEGATE?.httpPostRequest(APIKEY: APIKEY, requestURL: serviceURL, responseDict: RESPONSE_DATA, errorDict: RESPONSE_ERROR)
                    }
                }
            }catch {
                 DispatchQueue.main.async {
                RESPONSE_ERROR = "Check your input datas"
                self.HTTP_POST_STRING_REQUEST_DELEGATE?.httpPostRequest(APIKEY: APIKEY, requestURL: serviceURL, responseDict: RESPONSE_DATA, errorDict: RESPONSE_ERROR)
            }
            }
        } else {
            DispatchQueue.main.async {
                RESPONSE_ERROR = (error?.localizedDescription)!
                self.HTTP_POST_STRING_REQUEST_DELEGATE?.httpPostRequest(APIKEY: APIKEY, requestURL: serviceURL, responseDict: RESPONSE_DATA, errorDict: RESPONSE_ERROR)
            }
        }
    })
    task.resume()
}
ios swift server base64 uiimagepickercontroller
1个回答
0
投票

似乎您正在尝试将base64字符串作为查询字符串发送。成为查询字符串太长了。您需要共享POSTRequest方法的详细信息。有关更多信息。

Network.shared.POSTRequest(withParameterString: parameterStr, serviceURL: SAVE_PHOTO_LISTING, APIKEY: "SAVE_PHOTO_LISTING")

并且您需要避免在应用程序中使用感叹号(!)。您的代码将在许多方面崩溃。例如:

if Reachability()?.isReachable

您可以使用可选的值来防止崩溃。

 let parameters = ["property_id":self.PropertyID,
                "photos":base64 ?? "",
                "lang_code":lanuguage_selection.value(forKey: "language") ?? "en",
                "base_id":id,
                "user_id":login_session.value(forKey: "UserId") ?? ""];
 Network.shared.POSTRequest(parameters: parameters, serviceURL: SAVE_PHOTO_LISTING, APIKEY: "SAVE_PHOTO_LISTING")

在方法中添加json数据:

if let jsonData = try? JSONSerialization.data(withJSONObject: parameters) {
    request.httpBody?.append(jsonData)
}
© www.soinside.com 2019 - 2024. All rights reserved.