0

basically this profile image and when I add a picture from library and I try to patch image file name and save it on server but I get this error : "Unexpectedly found nil while unwrapping an Optional value: file" in the line of below that I sign it : I don't know why this happen :

here is my function that I try patch image file name on server :

func changeImage(parameters : [[String: Any]]) {
    var semaphore = DispatchSemaphore (value: 0)

   

    let boundary = "Boundary-\(UUID().uuidString)"
    var body = ""
    var error: Error? = nil
    for param in parameters {
      if param["disabled"] == nil {
        let paramName = param["key"]!
        body += "--\(boundary)\r\n"
        body += "Content-Disposition:form-data; name=\"\(paramName)\""
        if param["contentType"] != nil {
          body += "\r\nContent-Type: \(param["contentType"] as! String)"
        }
        let paramType = param["type"] as! String
        if paramType == "text" {
          let paramValue = param["value"] as! String
          body += "\r\n\r\n\(paramValue)\r\n"
        } else {
          let paramSrc = param["src"] as! String

            let fileData = try? NSData(contentsOfFile: paramSrc,options: [])
          as Data
// @@@@@@ this the line that got me error on debug area 
            let fileContent = String(data: fileData! as Data, encoding: .utf8)
          body += "; filename=\"\(paramSrc)\"\r\n"
            + "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
        }
      }
    }
    body += "--\(boundary)--\r\n";
    let postData = body.data(using: .utf8)

    var request = URLRequest(url: URL(string: "https://api.offernews.co/api/user")!,timeoutInterval: Double.infinity)
    request.addValue("baerar \(profileKeychain["token"]!)", forHTTPHeaderField: "Authorization")
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    request.httpMethod = "PATCH"
    request.httpBody = postData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
      guard let data = data else {
        print(" this is error that you need to know  \(String(describing: error))")
        semaphore.signal()
        return
      }
      print(" this the data that you need to complete  \(String(data: data, encoding: .utf8)!)")
      semaphore.signal()
    }

    task.resume()
    semaphore.wait()
}

and also this my picker image when I call the top function :

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
    if let image = info[.editedImage] as? UIImage {
        profileImage.image = image
        
        if let imageURL = info[.imageURL] as? URL {
           // let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
            let asset = imageURL.description
            if asset.contains("file://") {
                let changableURl = asset.replacingOccurrences(of: "file://", with: "")
                print(changableURl)
                let parameters = [
                         [
                           "key": "image",
                           "src": "\(changableURl)",
                           "type": "file"
                         ]] as [[String : Any]]
               changeImage(parameters: parameters)
            }
            
            print("this is the asset \(asset)")
           // print(asset?.value(forKey: "filename"))

        }
     // print("  this is url of image :   \(info.description) ")
        print("this isssssssssss \(info.values.description)")
        if (info[.mediaURL] != nil) {
                       print(" this is provided for you \(String(describing: info[.mediaURL]))")
                   }
        
        if  saveImage(image: image) == true {
            
            print("this successeful photo image")
            
        }
    } else if let image = info[.originalImage] as? UIImage {
        print("   this is a test   \(info.values.description)")
        if (info[.mediaURL] != nil) {
            print(" this is provided for you \(String(describing: info[.mediaURL]))")
        }

        print("  this is url of image :   \(info.description) ")

        profileImage.image = image
        
    }
    dismiss(animated: true, completion: nil)
         
}    

if you have any idea share it , thank for your time that you put in for help.

Ali kazemi
  • 84
  • 6

0 Answers0