gpt4 book ai didi

ios - iPhone使用swift 4上传照片

转载 作者:行者123 更新时间:2023-11-28 07:51:28 25 4
gpt4 key购买 nike

我尝试使用 swift 4 将照片从 iPhone 上传到服务器,但出现以下错误:

2018-03-29 09:49:14.145010+0530 UploadPhoto[966:16059] [MC] Lazy loading NSBundle MobileCoreServices.framework
2018-03-29 09:49:14.145873+0530 UploadPhoto[966:16059] [MC] Loaded MobileCoreServices.framework
2018-03-29 09:49:19.747734+0530 UploadPhoto[966:16059] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/nalin/Library/Developer/CoreSimulator/Devices/7846FF4C-D495-4B7B-BAA6-EF298F8EC805/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2018-03-29 09:49:19.748561+0530 UploadPhoto[966:16059] [MC] Reading from private effective user settings.
2018-03-29 09:49:22.983192+0530 UploadPhoto[966:16134] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
The data couldn’t be read because it isn’t in the correct format.

我为此编写的代码如下:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var uiSelectedImage: UIImageView!
@IBOutlet var tfImageName: UITextField!
@IBOutlet var btSelectImage: UIButton!
@IBOutlet var btUploadImage: UIButton!

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func selectImage(_ sender: UIButton) {
let imagePickerController = UIImagePickerController();
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary;
self.present(imagePickerController, animated: true, completion: nil)
}

@IBAction func uploadImage(_ sender: UIButton) {
let image = uiSelectedImage.image;
let imageData = UIImageJPEGRepresentation(image!, 1.0);

let url = URL(string: "http://192.168.43.174/LoginAndRegister/SavePictures.php");
let session = URLSession(configuration: URLSessionConfiguration.default);
var request = URLRequest(url: url!);
request.httpMethod = "POST";

//creating boundry constant
let boundaryConstant = "----------------12345";
let contentType = "multipart/form-data;boundary=" + boundaryConstant
request.setValue(contentType, forHTTPHeaderField: "Content-Type");

//making variable to send post data
let uploadData = NSMutableData();

//adding image to be uploaded in post data
uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!);
uploadData.append("Content-Disposition: form-data; name=\"picture\"; filename=\"file.png\"\r\n".data(using: String.Encoding.utf8)!);
uploadData.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append(imageData!);
uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!);

request.httpBody = uploadData as Data;

let task = session.dataTask(with: request)
{
(data:Data!, response: URLResponse!, error:Error!) in

if error != nil
{
print(error);
return;
}

do
{
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String:Any];
print(jsonResponse);
}
catch
{
print(error.localizedDescription);
}
}
task.resume();
}

@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
uiSelectedImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage;
self.dismiss(animated: true, completion: nil);
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}

服务器端如下:

<?php
$name = $_POST["name"];
$image = $_POST["image"];

$decodeImage = base64_decode("$image");
if(file_put_contents("pictures/" . $name . ".JPG", $decodeImage) === FALSE)
{
$result = array('success' => "false", 'result' => "Unable to upload image");
}
else
{
$result = array('success' => "true", 'result' => "Image Uploaded Successfully");
}

echo json_encode($result);
?>

最佳答案

请使用 alamofire 上传图片..

func CompleteShipmentAPI(){

let imgData = UIImageJPEGRepresentation(signatureImageView.image!, 0.25)!

let ShipID:NSNumber = mdicShipmentDetails.value(forKey: "id") as! NSNumber

// userDetails
let paramerers:Parameters = ["ship_id":ShipID.stringValue]

print(paramerers)

MBProgressHUD.showAdded(to: self.view, animated: true)

let headers: HTTPHeaders = [
"x-api-key": AUTH_API_KEY
]
let isImageOnProducts:NSNumber = mdicShipmentDetails.value(forKey: "isImageOnProducts") as! NSNumber
let isDigitalSignature:NSNumber = mdicShipmentDetails.value(forKey: "isDigitalSignature") as! NSNumber

Alamofire.upload(multipartFormData: { multipartFormData in

if isDigitalSignature.stringValue == "1"{
//SHOW
multipartFormData.append(imgData, withName: "shipment_sign",fileName: "signature.jpg", mimeType: "image/jpg")
}

for (key, value) in paramerers {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key )
}
},to:BASE_URL+kPOST_COMPLETE_API, headers:headers){ (result) in
switch result {
case .success(let upload, _, _):

upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})

upload.responseString { response in

MBProgressHUD.hide(for: self.view, animated: true)

if let strResponse:String = response.result.value {
print(strResponse)

}
}

case .failure(let encodingError):
print(encodingError)
MBProgressHUD.hide(for: self.view, animated: true)
}
}
}

关于ios - iPhone使用swift 4上传照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com