В моем приложении я выбрал изображение, используя UIImagePickerController
из фотографий, а затем сжал и преобразовал в base64 string
, наконец, я загружаю строку base64 на сервер.Здесь сервер не принимает base64 string
и не работает, но в Android
и почтальоне это работает хорошо.Я не мог знать, в чем ошибка в моем коде, пожалуйста, помогите мне решить проблему.
Здесь я упоминаю 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()
}