iPhone上传照片使用swift 4

时间:2018-03-29 04:29:01

标签: ios iphone swift

我试图使用swift 4将照片从iPhone上传到服务器,但我收到以下错误,

  

2018-03-29 09:49:14.145010 + 0530 UploadPhoto [966:16059] [MC]延迟加载NSBundle MobileCoreServices.framework   2018-03-29 09:49:14.145873 + 0530 UploadPhoto [966:16059] [MC]已加载MobileCoreServices.framework   2018-03-29 09:49:19.747734 + 0530 UploadPhoto [966:16059] [MC] systemgroup.com.apple.configurationprofiles路径的系统组容器是/ Users / nalin / Library / Developer / CoreSimulator / Devices / 7846FF4C-D495 -4B7B-BAA6-EF298F8EC805 /数据/容器/共享/ SystemGroup / systemgroup.com.apple.configurationprofiles   2018-03-29 09:49:19.748561 + 0530 UploadPhoto [966:16059] [MC]从私人有效用户设置中读取。   2018-03-29 09:49:22.983192 + 0530 UploadPhoto [966:16134] [发现]发现扩展时遇到的错误:错误域= PlugInKit代码= 13"查询已取消" UserInfo = {NSLocalizedDescription =查询已取消}   无法读取数据,因为格式不正确。

我写的代码如下,

    +--------------------------+-----------------------------------------------+
| Variable_name            | Value                                         |
+--------------------------+-----------------------------------------------+
| character_set_client     | ascii                                         |
| character_set_connection | ascii                                         |
| character_set_database   | latin1                                        |
| character_set_filesystem | binary                                        |
| character_set_results    | ascii                                         |
| character_set_server     | latin1                                        |
| character_set_system     | utf8                                          |
| character_sets_dir       | /rdsdbbin/oscar-5.6.10a.31.59/share/charsets/ |
+--------------------------+-----------------------------------------------+

服务器方面如下,

    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)
}
}

请帮助我,谢谢你。

3 个答案:

答案 0 :(得分:0)

请用户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)
        }
    }
}

答案 1 :(得分:0)

使用let parameter: [String: Any] = [ "user_id": 12, "image": ImageStructInfo(fileName: "image.jpg", type: "image/jpg", data: #imageLiteral(resourceName: "TempImage").toData()) ]

在GitHub AGUploadImage上查找我的自定义课程

您可以发送单个和多个图像,在ImageStructInfo结构上设置参数键和图像信息,如。

AGUploadImage(url: "Url", parameter: parameter).responseJSON { (data, error) in
    if error != nil{
        print("error")
    }
    else{
        print(data)
    }
}

上传图片代码很简单,使用clouser,代码如下。

{{1}}

答案 2 :(得分:0)

我使用以下代码使用Alamofire上传图片

@IBOutlet var Imgprofile: UIImageView!

func uploadImage(){

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(self.Imgprofile.image!, 1)!, withName: "Prescription", fileName: "Profile_Image.jpeg", mimeType: "image/jpeg")
    }, to:"http://192.168.1.86/PharmacyWS/uploadprescription")
    { (result) in
        switch result {
        case .success(let upload, _, _):
            print(result)

            upload.uploadProgress(closure: { (progress) in
                print(progress)
            })

            upload.responseJSON { response in
                //print response.result
                print(response);
            }

        case .failure(let encodingError):
            print(encodingError);
        }
    }
}