2017-08-29 1 views
0

J'essayais de télécharger une image dans l'API IMAGGA et de récupérer des tags de reconnaissance d'image pour mon projet, mais je n'arrive pas à obtenir les tags souhaités. J'ai utilisé Alamofire pour télécharger l'image, mais je reçois cette erreur et aucun tag de l'appel de l'API.Utilisation d'Imagga API et d'Alamofire

Voici la fonction que j'ai utilisée pour télécharger l'image. code:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
      defer { 
       picker.dismiss(animated: true) 
      } 

      print(info) 
      // get the image 
      guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { 
       return 
      } 

      imageView.image = image 


      let documentDirectory: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString 

      let imageName = "temp" 
      let imagePath = documentDirectory.appendingPathComponent(imageName) 

      if let data = UIImageJPEGRepresentation(image, 80) { 
       // Save cloned image into document directory 
       let urlFile = NSURL(string: imagePath) 

       do { 
        try data.write(to: urlFile! as URL, options: .atomic) 
       } catch { 
        print(error) 
       } 
       // Save it's path 
       localPath = imagePath 
      } 

      let imageData = UIImagePNGRepresentation(image)! 

    // 

      let headers: HTTPHeaders = [ 
       "Authorization": "Basic YWNjX2MwNDUzYzkzNTEyOGNkYzo0ZmE5MWM4Zjg0MDk1ZGI0NGE2ZjNjODJkNTczZDUxOQ==", 
       "Accept": "application/json" 
      ] 

      Alamofire.request("https://httpbin.org/basic-auth/\("acc_c0453c935128cdc")/\("4fa91c8f84095db44a6f3c82d573d519")", parameters: ["url": "http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg"], headers: headers) 
       .authenticate(user: "acc_c0453c935128cdc", password: "4fa91c8f84095db44a6f3c82d573d519") 
       .responseJSON { response in 
        debugPrint(response) 
        switch(response.result) { 
        case .success(_): 
         if let data = response.result.value{ 


          print("YOUR JSON DATA>> \(response.data!)") 


         } 
         break 

        case .failure(_): 
         print(response.result.error) 


         break 

        } 

      } 



     } 

Je reçois ce que l'erreur. Il montre du succès à la fin mais je ne suis pas sûr si l'image est envoyée à l'imagga pour la reconnaissance d'image ou pas.

Error: 

    URL which has no scheme 
    Error Domain=NSCocoaErrorDomain Code=518 "The file couldn’t be saved because the specified URL type isn’t supported." UserInfo={NSURL=/var/mobile/Containers/Data/Application/D8A0EE1D-2092-474F-B21A-8A7E0635AD40/Documents/temp} 
    [Request]: GET https://httpbin.org/basic-auth/acc_c0453c935128cdc/4fa91c8f84095db44a6f3c82d573d519?url=http%3A//docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg 
    [Response]: <NSHTTPURLResponse: 0x1702210e0> { URL: https://httpbin.org/basic-auth/acc_c0453c935128cdc/4fa91c8f84095db44a6f3c82d573d519?url=http%3A//docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg } { status code: 200, headers { 
     "Access-Control-Allow-Credentials" = true; 
     "Access-Control-Allow-Origin" = "*"; 
     Connection = "keep-alive"; 
     "Content-Length" = 62; 
     "Content-Type" = "application/json"; 
     Date = "Tue, 29 Aug 2017 16:42:07 GMT"; 
     Server = "meinheld/0.6.1"; 
     Via = "1.1 vegur"; 
     "X-Powered-By" = Flask; 
     "X-Processed-Time" = "0.000633001327515"; 
    } } 
    [Data]: 62 bytes 
    [Result]: SUCCESS: { 
     authenticated = 1; 
     user = "acc_c0453c935128cdc"; 
    } 
    [Timeline]: Timeline: { "Request Start Time": 525717726.320, "Initial Response Time": 525717728.876, "Request Completed Time": 525717728.882, "Serialization Completed Time": 525717728.889, "Latency": 2.556 secs, "Request Duration": 2.562 secs, "Serialization Duration": 0.006 secs, "Total Duration": 2.569 secs } 
    YOUR JSON DATA>> 62 bytes 
+0

Ne publiez jamais de clés api sur des forums publics. – nathan

Répondre

0

Peut-être parce que vos paramètres ne sont pas encodés correctement. Votre question mentionne Imagga mais vous utilisez httpbin pour le débogage.

Voici un exemple concret de l'API Alamofire + Imagga:

Utiliser une image distante

let parameters: Parameters = [ 
     "version" : 2, 
     "url" : "http://playground.imagga.com/static/img/example_photo.jpg" 
    ] 
    var headers: HTTPHeaders = [ 
     "Accept" : "application/json" 
    ] 

    // Three ways to add the auth header (3rd is to use authenticate method): 
    // 1. Append the basic encoded value already provided by Imagga's dashboard 
    // headers["Authorization"] = "Basic xxxxxx==" 
    // 2. Construct the header using the api key + api secret 
    if let authorizationHeader = Request.authorizationHeader(user: "api_ley", password: "api_secret") { 
     headers[authorizationHeader.key] = authorizationHeader.value 
    } 

    Alamofire 
     .request("http://api.imagga.com/v1/tagging", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers) 
     .responseJSON { (response) in 
      print(response) 
    } 

Réponse:

{ 
    "results": [ 
    { 
     "tagging_id": null, 
     "image": "http://playground.imagga.com/static/img/example_photo.jpg", 
     "tags": [ 
     { 
      "confidence": 71.4296152834829, 
      "tag": "beach" 
     }, 
     { 
      "confidence": 52.843097989562466, 
      "tag": "sea" 
     }, 
     { 
      "confidence": 46.13550857065488, 
      "tag": "sun" 
     }, 
     { 
      "confidence": 43.923454585374714, 
      "tag": "ocean" 
     }, 
     { 
      "confidence": 43.23227098537762, 
      "tag": "water" 
     }, 
     { 
      "confidence": 7.113114870093362, 
      "tag": "leisure" 
     } 
     ] 
    } 
    ] 
} 

Téléchargement d'une image locale

Comme th La documentation mentionne que vous devez télécharger l'image au point de terminaison content en premier.

struct de réponse simple à faire JSON l'analyse syntaxique plus facile (Swift 4. Devrait être assez facile à utiliser Swift 3, mais plus fastidieux):

struct ImaggaContentResponse: Decodable { 
    let status: String 
    let message: String? 
    let uploaded: [ImaggaContent] 

    struct ImaggaContent: Decodable { 
     let id, filename: String 
    } 
} 


/// Represents the available sources for images 
/// 
/// - url: Represents a remote images (URL must be specified) 
/// - content: Represents a previously uploaded local image to the content endpoint (content id must be provided) 
enum ImaggaImageOrigin { 
    case url(String) 
    case content(String) 
} 


Exemple:

class ViewController: UIViewController { 

    var headers: HTTPHeaders = { 
     var defaultheaders = [ 
      "Accept" : "application/json" 
     ] 
     if let authorizationHeader = Request.authorizationHeader(user: "api_key", password: "api_secret") { 
      defaultheaders[authorizationHeader.key] = authorizationHeader.value 
     } 

     return defaultheaders 
    }() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let imageData = UIImage.make(from: .purple).jpeg! 
     Alamofire.upload(
      multipartFormData: { (multipartFormData) in 
      multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg") 
     }, 
     to: "https://api.imagga.com/v1/content", 
     method: .post, 
     headers: headers, 
     encodingCompletion: { (result) in 
      switch result { 
      case .success(let upload, _, _): 
       upload.uploadProgress(closure: { (progress) in 
        print(progress) 
       }) 
       upload.responseData { response in 
        guard let jsonData = response.value, 
         let contentResponse = try? JSONDecoder().decode(ImaggaContentResponse.self, from: jsonData) 
         else { return } 

        let firstImage = contentResponse.uploaded.first! 
        self.tagImage(from: .content(firstImage.id)) 
       } 
      case .failure(let encodingError): 
       print (encodingError) 
      } 
     }) 
    } 

    func tagImage(from source: ImaggaImageOrigin) { 
     var parameters: Parameters = [ 
      "version" : 2, 
     ] 

     switch source { 
     case .url(let imageUrl): 
      parameters["url"] = imageUrl 
     case .content(let contentId): 
      parameters["content"] = contentId 
     } 

     Alamofire 
      .request("http://api.imagga.com/v1/tagging", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers) 
      .responseString { (response) in 
       print(response) 
     } 
    } 
}