附加数据以发布正文并上传到api

时间:2018-12-09 15:13:23

标签: ios iphone swift xcode data-access

我通过传递一些参数来调用一个api,包括从icloud中获取pdf,doc,docx等文件并调用api。

现在我正在从icloud中选择一些文件,我需要传递给api调用。问题是我的选择文件(pdf或doc)没有转换为nsdata并且字节为0。所以它不符合我的身体参数。请帮我解决我做错的地方

我的代码:

func uploadthefileToserver(){

    if let url = URL(string: "https://www.exampleurl/api"){
        var request = URLRequest(url: url)
        let boundary:String = "Boundary-\(UUID().uuidString)"
        // let request = NSMutableURLRequest(url:myUrl! as URL);
        request.httpMethod = "POST"
        request.timeoutInterval = 10
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        let postJobData:[String:Any] = ["UserId":"107","name":"hardcodevalue"]
        var dataFile: Data = Data()
        print(fullDestPath)   ///Users/sathish/Library/Developer/CoreSimulator/Devices/4464E7A8-0F38-4802-B645-19721D251054/data/Containers/Data/Application/714B1B8E-5872-42B9-B963-B0C51C9403D7/Documents/NewFileiCloud/iOS.DOCX"
        do{
            dataFile = try NSData.init(contentsOf: URL(fileURLWithPath: fullDestPath, isDirectory: true)) as Data
            print(dataFile)
        }catch{
            print(error)
        }
        if(dataFile==nil)  { return; }
        print(dataFile) //0 bytes
        request.httpBody = createBodyWithParameters(parameters: postJobData, filePathKey: "Resume", FileData: dataFile as NSData , boundary: boundary) as Data
        print(postJobData)
        print(dataFile)

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in


            if error != nil {
                print("error=\(error)")
                return
            }else if let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
                print("****** response data = \(responseString)")
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    print(json)

                    let status = json!["Success"] as! String
                    let errMessage = json!["Message"] as? String
                    DispatchQueue.main.async() {
                        if status == "1"{
                            print(errMessage)

                        }else{
                            print(errMessage)
                        }
                    }

                }catch{
                    print(error)
                }
            }

        }; task.resume()
    }
}

不确定我在哪里做错了。我添加了一些打印功能以供参考。

主要部分:

dataFile = try NSData.init(contentsOf: URL(fileURLWithPath:
fullDestPath, isDirectory: true)) as Data

request.httpBody = createBodyWithParameters(parameters: postJobData,
filePathKey: "Resume", FileData: dataFile as NSData , boundary:
boundary) as Data

谢谢

更新:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

        print("url = \(urls)")
        filePathUrl = urls
        print(filePathUrl)
        for urll in filePathUrl{
            filepath = filePathUrl[0] as! URL
            print(filepath)
            filePathString = filepath.path
            urlstr = NSURL(fileURLWithPath: filePathString).lastPathComponent!
            print(urlstr)
            // Data object to fetch weather data
            do {
                let weatherData = try NSData(contentsOf: filepath, options: NSData.ReadingOptions())
                print(weatherData)

            } catch {
                print(error)
            }

        }
        let destPath:NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
        let fileManager = FileManager.default
        print(destPath, "\n")
        documentDir = destPath[0] as? NSString
        let filePath = documentDir?.appendingPathComponent("NewFileiCloud") as! NSString

      //  if fileManager.fileExists(atPath: filePath as String){

            do {
               // try fileManager.createDirectory(atPath: filePath as String, withIntermediateDirectories: false, attributes: nil)
                fullDestPath = filePath.appendingPathComponent(urlstr)
                print(fullDestPath!) ///Users/sathish/Library/Developer/CoreSimulator/Devices/4464E7A8-0F38-4802-B645-19721D251054/data/Containers/Data/Application/E41634D7-681A-4C09-B3EF-5782CECCF4B0/Documents/NewFileiCloud/filke.pdf
                do{
                    try fileManager.copyItem(atPath: filePathString!, toPath: fullDestPath)
                }catch{
                    print("\n")
                    print(error)
                }
            }catch{
                print(error)
            }
       // }

      // ------- This is the path of the application stored filepath -------------- //

        filePathLabel.text = fullDestPath

// ------------------- ---------------------------------//
// Read a file content
        //     fileContent = fileManager.contents(atPath: fullDestPath as String ) as! NSData
        //       print(fileContent)

        uploadthefileToserver()
    }

 func createBodyWithParameters(parameters: [String: Any]?, filePathKey: String?, FileData: NSData, boundary: String) -> NSData {

        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString(string:"--\(boundary)\r\n")
                body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString(string: "\(value)\r\n")
            }
        }

        return body

        let filename = fullDestPath
        let mimetype = "pdf/docx/text"

        body.appendString(string: "--\(boundary)\r\n")
        body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
        body.append(FileData as Data)
        body.appendString(string: "\r\n")
        body.appendString(string: "--\(boundary)--\r\n")

        return body
    }

1 个答案:

答案 0 :(得分:0)

您正在尝试做,

  1. 将PDFURL转换为数据

  2. 将数据转换为.PDF

  3. 将.PDF存储在Doc.Dir文件中。

  4. 从Doc.Dir检索.PDF并将其传递到服务器。

对于上述任务,您必须在NewFileiCloud中创建文件夹Doc.Dir。然后,将pdfUrl转换为data并将数据写入.pdf文件,然后从.pdf获取该doc.dir路径并将其转换为{{1 }}并传递到Data

我为您做了样品。这会让您满意的。

server