0

I am using an API post request in order to get a modified image.

curl \
    -F 'image=@/path/to/your/file.jpg' \
    -H 'api-key:[myKey]' \
    [api url]

It worked fine directly on my Mac's terminal using:

curl \
    -F 'image=@/Users/user/image.jpg' \
    -H 'api-key:[myKey]' \
    [api url]

Trying to use it in an iOS app, I'm struggling to get an image path.

The api works with Alamofire using another parameter that uses an image url. So I thought to upload the image to a server and use that url, but it would be much better if I could use directly the path parameter.

This is what I tried, but it doesn't work.

func imagePath(_ image: UIImage, handler: @escaping (String?) -> Void ) {

    let path = NSTemporaryDirectory()
        .appending(UUID().uuidString)
        .appending("png")
    
    let url = URL(fileURLWithPath: path)
    
    let data = image.pngData()
    
    let urlForApi = "@" + path
    
    do {
        
        try data?.write(to: url)
        
        //  Just to check if write above works, it always works fine
        let postData = try UIImage(data: Data(contentsOf: url))
        
        handler (urlForApi)
        
    } catch {
        
        handler (nil)
        
    }
        
}

It returns handler(urlForApi), but the request gets an error. I'm not getting the correct path to use for the request.

Nico
  • 181
  • 1
  • 4
  • First of all `let urlForApi = "@" + path` <-- this is not needed, the "@" notation is CURL-specific syntax. Second: `/Users/user/` absolute path is quite different from `NSTemporaryDirectory()` – timbre timbre Nov 30 '20 at 19:56

1 Answers1

0

I could solve it using the Alamofire upload request.


func getPostURL(`fromImage` preImage: UIImage?, postImageURL: @escaping (_ outputImageURL: String) -> (), error: @escaping (_ error: Error?) -> ()) {
        
        if let safeImage = preImage {
            
            let data = safeImage.pngData()!
            
            AF.upload(multipartFormData: { (form) in
                form.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
            }, to: apiURL!, headers: headers).validate(statusCode: okStatusCodes).responseDecodable(of: ImageResponse.self) {
                
                response in
                
                if let url = response.value?.output_url {
                    postImageURL(url)
                } else {
                    error(response.error)
                }
                
            }
            
        } else {
            error(ImageDataError.gettingPostURL)
        }
        
        
    }

However, it would be interesting to know how to get temporary paths to files.

Nico
  • 181
  • 1
  • 4