php - 使用 alamofire 4 在 swift 4 中上传图像,php 在更新版本中不起作用

标签 php ios swift alamofire image-upload

我已经完成了我的项目,使用 php 脚本将图像上传到服务器。它在带有 alamofire 的 Swift 2 上运行良好。

使用 alamofire4 更新到 Swift 4 后,上传代码无法正常工作。

@IBAction func create(_ sender: AnyObject) {

    showLoadingMode (loading: self)

    let name = grpnametf.text
    let defaults = UserDefaults.standard

    let member_id = defaults.object(forKey: "id") as! String
    let country = defaults.object(forKey: "country") as! String


    if (name != "" ){

        self.reachability = Reachability.init()
        if((self.reachability?.connection) != .none)
        {
       // let reachability = Reachability2.reachabilityForInternetConnection()

        //if reachability.isReachable() || reachability.isReachableViaWiFi() || reachability.isReachableViaWWAN(){

        //if (network.reachability.whenReachable != nil) {
            let image : NSData = UIImageJPEGRepresentation(profileimg.image!, 32)! as NSData


          //let picname = "1"
            let grpiconname : String = member_id + name!

            let formattedstring = grpiconname.replacingOccurrences(of: " ", with: "_")

            let parameters = [
                "id" : member_id,
                "g_name" : name!,
                "type" : "ios",
                "country" : country,
                "fileName" : formattedstring+".jpg"

                ]
            let url = "http://www.kidsedin.com/nriconnect/webpage/index.php/App/creategroup"

            Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in

                if let j = response.result.value {


                    actInd.stopAnimating()

                    //swifty json

                    // print(j)
                    let result = (j as AnyObject).stringValue
                   // print (result)

                    if result != "0" {

                       // let urlRequest = self.urlRequestWithComponents(urlString: "http://www.kidsedin.com/nriconnect/webpage/index.php/app/pic_upload?grpicon_name="+formattedstring+"&groupid="+result!, parameters: parameters as NSDictionary)

                        //print(urlRequest)

                       // let imageToUploadURL = Bundle.main.url(forResource: "bg", withExtension: "jpg")

                        //let url = "http://www.kidsedin.com/nriconnect/webpage/index.php/app/testpicupload"

                            // Use Alamofire to upload the image

                        print(UIImageJPEGRepresentation(self.profileimg.image!, 1))
                        Alamofire.upload(multipartFormData: { (multipartFormData) in
                            multipartFormData.append(UIImageJPEGRepresentation(self.profileimg.image!, 0.2)!, withName: "photo_path", fileName: formattedstring+".jpg", mimeType: "image/jpeg")
                            for (key, value) in parameters {
                                multipartFormData.append(value.data(using: .utf8)!, withName: key)
                            }
                        }, to:"http://www.kidsedin.com/nriconnect/webpage/index.php/app/testpicupload?grpicon_name="+formattedstring+"&groupid="+result!+"&type=ios")
                        { (result) in
                            switch result {
                            case .success(let upload, , ):

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

                                upload.responseJSON { response in
                                    print(response.result.value)
                                    print("1")
                                }

                            case .failure(let encodingError): break
                                //print(encodingError.localizedDescription)
                            }
                        }
                    }

                    else if result == "0"{

                        let alert = UIAlertController(title: "", message: "Group name already exist", preferredStyle: .alert)
                        let okAction = UIAlertAction(title: "Ok", style: .default, handler:nil)
                        alert.addAction(okAction)

                        self.present(alert, animated: true, completion: nil)


                        actInd.stopAnimating()

                    }else
                    {
                        let alert = UIAlertController(title: "", message: "Group creation failed. Something went wrong", preferredStyle: .alert)
                        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

                        alert.addAction(okAction)

                        self.present(alert, animated: true, completion: nil)

                        actInd.stopAnimating()
                    }
                }

            }
        }

        else
        {
            //print("Internet connection FAILED")
            let alert = UIAlertController(title: "No internet connection. Please check it", message: "Make sure your device is connected to the internet.", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

            alert.addAction(okAction)

            self.present(alert, animated: true, completion: nil)


            actInd.stopAnimating()
        }
    }

    else{

        if( name == "" ){

            let alert = UIAlertController(title: "", message: "Name field is empty", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

            alert.addAction(okAction)

            self.present(alert, animated: true, completion: nil)

            actInd.stopAnimating()
        }

    }
}

以上是我更新的代码。请建议我应该做什么来解决这个错误。或者使用 php 脚本为我提供此图像上传的替代解决方案。

最佳答案

its maybe helps you

import Foundation
import Alamofire

class UploadImageController: NSObject {

// MARK: - shared

static let shared  = UploadImageController()

// MARK: - init

let decoder = JSONDecoder()

// MARK: - uploadImageOnly

func uploadImageWith(endUrl: String, photo: UIImage?, parameters: [String : Any]?, headers: HTTPHeaders?, completion: @escaping (_ success: Bool, _ uploadImageResponse: UploadImageResponse?) -> Void ) {

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        if let data = UIImageJPEGRepresentation(photo!, 0.5) {

            multipartFormData.append(data, withName: "invoice", fileName: "invoice.jpeg", mimeType: "invoice/jpeg")
        }

    }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: endUrl, method: .post, headers: headers) { (result) in

        switch result {

        case .failure(let error):
            print("UploadImageController.requestWith.Alamofire.usingThreshold:", error)
            completion(false, nil)

        case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):

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

            upload.responseJSON(completionHandler: { (response) in

                switch response.result {

                case .failure(let error):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON:", error)

                    completion(false, nil)

                case .success( _):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON Succes")
                    guard let data = response.data else { return }

                    do {

                        let uploadImageResponse = try self.decoder.decode(UploadImageResponse.self, from: data)

                        completion(true, uploadImageResponse)

                    } catch let jsonError {

                        print("Error serializing json.ProfileController.getProfile:", jsonError)
                        completion(false, nil)
                    }
                }
            })
        }
    }
}

// MARK: - uploadImageWithParameters

func uploadImageWithParametersAnd(endUrl: String, photo: UIImage?, parameters: [String : Any]?, headers: HTTPHeaders?, completion: @escaping (_ success: Bool, _ addInvoiceResponse: AddInvoiceResponse?) -> Void ) {

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        if let data = UIImageJPEGRepresentation(photo!, 0.5) {

            multipartFormData.append(data, withName: "invoicePicture", fileName: "invoicePicture.jpeg", mimeType: "invoice/jpeg")
        }

        for (key, value) in parameters! {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: "\(key)")
        }


    }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: endUrl, method: .post, headers: headers) { (result) in

        switch result {

        case .failure(let error):
            print("UploadImageController.requestWith.Alamofire.usingThreshold:", error)
            completion(false, nil)

        case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):

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

            upload.responseJSON(completionHandler: { (response) in

                switch response.result {

                case .failure(let error):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON:", error)

                    completion(false, nil)

                case .success( _):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON Succes")
                    guard let data = response.data else { return }

                    do {

                        let addInvoiceResponse = try self.decoder.decode(AddInvoiceResponse.self, from: data)

                        completion(true, addInvoiceResponse)

                    } catch let jsonError {

                        print("Error serializing json.ProfileController.getProfile:", jsonError)
                        completion(false, nil)
                    }
                }
            })
        }
    }
 }
}

关于php - 使用 alamofire 4 在 swift 4 中上传图像,php 在更新版本中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50835861/

相关文章:

ios - 如何从 iOS Swift 中的框架中关闭相机 Controller ?

iOS,如何在同一 View 上播放多个视频?

swift - Set的contains方法在不同时间返回不同的值

ios - 从推送通知启动时,launchOptions 始终为零

ios - 将数组传递给单例(swift)

php - 获取数组中的 Youtube VideoID 详细信息

php - 通过ajax创建的post变量

ios - 什么指定了 UITextField 的占位符对齐方式?

php - 如何在 postman RESTful Web 服务中发送多个文件?

php - Mysql 在字段 : 中添加 NULL 值