2017-08-29 83 views
0

我試圖上傳一個圖像到IMAGGA API並找回我的項目的一些圖像識別標籤,但我無法獲得所需的標籤。我用Alamofire上傳圖片,但我得到這個錯誤,並沒有來自API調用的標籤。使用Imagga API和Alamofire

這是我用來上傳圖片的功能。 代碼:

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 

        } 

      } 



     } 

我得到這個錯誤。它最終顯示了成功,但我不確定圖像是否被髮送到圖像識別的圖像。

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

切勿在公共論壇上張貼api密鑰。 – nathan

回答

0

可能是因爲您的參數編碼不正確。你的問題提到Imagga,但你正在使用httpbin進行調試。

這裏的Alamofire + Imagga的API的工作示例:

使用遠程圖像

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) 
    } 

響應:

{ 
    "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" 
     } 
     ] 
    } 
    ] 
} 

上傳本地圖片

由於日e文檔提到,您需要首先將映像上傳到content端點。

簡單響應的結構,使JSON解析容易(斯威夫特4.應該是很容易使用,斯威夫特3,但比較繁瑣):

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) 
} 


樣品:

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) 
     } 
    } 
}