2016-10-04 3 views
5

코드를 Swift 3으로 업데이트했으며 Alamofire 4.0으로의 마이그레이션에 문제가 있습니다. 필자는 Alamofire 마이그레이션 가이드를 사용하여 필요한 수정 작업을 성공적으로 수행했지만 이미지 데이터를 가져 오는 데는 여전히 문제가 있습니다. (의도 한대로 일)Alamofire 요청으로 이미지 데이터 가져 오기

오래된 스위프트 2/Alamofire 3 코드 : Alamofire 4 으로 업데이트에서

func beginGetImageRequest() { 
    if let imagePath = thumbPath { 
     request = Alamofire.request(.GET, imagePath).response(completionHandler: { (_, _, imageData, error) -> Void in 
      if error != nil { 
       NSLog("Error downloading thumbnail image: \(error)") 
      } else { 
       if let downloadedImage = UIImage(data: imageData!) { 
        self.imageView.image = downloadedImage 
       } 
      } 
     }) 
    } 
} 

내 시도 :

func beginGetImageRequest() { 
    if let imagePath = thumbPath { 
     request = Alamofire.request(imagePath, method: .get, parameters: [:], encoding: JSONEncoding.default) 
      .validate { request, response, imageData in 
       if let downloadedImage = UIImage(data: imageData!) { 
        self.imageView.image = downloadedImage 
       } else { 
        print(response) 
        print(imageData) 
       } 
       return .success 
      } 
    } 
} 

print(imageData) 출력 Optional(306 bytes). 이미지는 UIImage로 데이터를 변환하는 방법이 아니라 요청을 구현하는 방법에 문제가 있음을 알려주는 약 40KB 여야합니다. 여기

는 대부 위의 의견에 제안처럼, print(response)

<NSHTTPURLResponse: 0x618000221660> { URL: http://209.126.98.238/cache/igames_thumb/images/games/53848027743af.jpeg } { status code: 400, headers { 
    Connection = close; 
    "Content-Encoding" = gzip; 
    "Content-Length" = 245; 
    2016-10-04 21:54:53.653480 EyeGames[74216:3416747] [] nw_connection_send_stats_report 21 Generated report: 
    Delegated:         0 
    Report reason:        app data stall 
    TCP statistics report:      
    Time to DNS start:      0 ms 
    Time to DNS resolved:     0 ms 
    DNS resolved time:      0 ms 
    DNS answers cached:      0 
    Interface type:       1 
    Time to TCP start:      3 ms 
    Time to TCP establishment:    223 ms 
    Connection establishment:    220 ms 
    Flow duration:       11447 ms 
    Connected interface type:    1 
    Connected:        1 
    Traffic class:       0 
    Cellular fallback:      0 
    Cellular RRC connected:     0 
    Kernel reported stalls:     0 
    Kernel reported connection stalls:  0 
    Kernel reported read stalls:    0 
    Kernel reported write stalls: 
"Content-Type" = "text/html; charset=iso-8859-1"; 
    Date = "Tue, 04 Oct 2016 18:54:43 GMT"; 
    Server = "Apache/2.2.22 (Debian)"; 
    Vary = "Accept-Encoding"; 
} } 
+0

Alamofire.request 그리고 무엇 응답이 포함를 호출하기 전에 URL에 대한 캐시를 제거 할 수 있습니까? 당신은 거기에서 시작해야합니다 – Godfather

+0

@ Godfather 응답에서 출력을 포함하도록 내 질문을 편집했습니다 –

+0

당신은 400 오류 코드를 받고 있습니다. 요청이 잘못되었습니다. 인코딩을 URL로 변경해보십시오 – Godfather

답변

14

의 사람들 이상은, AlamofireImage 이미지 구성 요소 라이브러리를했다. 그것은 당신이 당신의 인생을 더 쉽게 만드는 모든 것들을 처리합니다. 그것을 당신의 프로젝트에 추가하면 다음과 같이 할 수 있습니다 :

import Alamofire 
import AlamofireImage 

Alamofire.request(imageUrl, method: .get).responseImage { response in 
    guard let image = response.result.value else { 
     // Handle error 
     return 
    } 
    // Do stuff with your image 
} 
+0

이것은 완벽합니다! 이 구성 요소 라이브러리에 대해 몰랐습니다. 고맙습니다! –

+1

AlamofireImage를 사용하려면 프로젝트에 Alamofire 및 AlamofireImage를 추가해야하며 위 코드를 실행하려면 AlamofireImage 만 추가하면됩니다. –

2

당신이 정말로 이미지를 다운로드하는 Alamofire을 사용하려면, 대신 JSONEncoding의에는 urlencoding 시도해야의 출력이다. 대신 Kingfisher를 사용하는 것이 좋습니다. 그것은 Alamofire 당신에게 단 한 줄의 코드 대신 GET 요청 방식을 취합니다 Alamofire에서

self.imageView.kf.setImage(with: URL(string: imagePath)) 
+0

내 프로젝트가 이미지 및 이미지 이외의 문제에 대해 이미 Alamofire에 크게 의존하고 있기 때문에 Alamofire를 계속 사용하는 것이 좋습니다. 하지만 앞으로의 프로젝트에서 Kingfisher를 염두에 두겠습니다. 귀하의 의견을 보내 주셔서 감사합니다! –

0

이전에 저장된 이미지를 가져올 때 이미지 캐시 문제가 발생할 수 있습니다. 이를 방지하기 위해

, 당신은

let urlRequest = URLRequest(url: URL(string: url)!) 
URLCache.shared.removeCachedResponse(for: urlRequest)