2015-02-02 4 views
1

Im 문제가 발생했습니다. 매개 변수로 PFObject를 허용하는 메서드를 만들려고합니다. 이 경우 PFObject는 페이스 북 그림 URL입니다. 이 메서드는 URL을 가져 와서 기본적으로 이미지로 변환합니다. 나는이 코드 블록을 메서드로 만들지 않고이 코드 블록을 사용하면 작동하도록 만들 수 있습니다. 그러나이 메서드를 만들어서 반복하지 않아도됩니다. 내가 사용자의 이미지를 반환 할 때 나는 오류가 sendAsynchronousRequestcompletionHandler 당신에게 전달하는 정의라고보고하고있다표현식 형식 UIImage를 void swift로 변환 할 수 없습니다. swift

func downloadFBUserImage(object: PFObject?) -> UIImage? { 
var userProfilePhotoURLString = object?.valueForKey("pictureURL") as String? 
if userProfilePhotoURLString != nil { 
    var pictureURL: NSURL = NSURL(string: userProfilePhotoURLString!)! 
    var urlRequest: NSURLRequest = NSURLRequest(URL: pictureURL) 
    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (NSURLResponse response, NSData data, NSError error) -> Void in 
     if error == nil && data != nil { 
      var userProfilePic: UIImage? = UIImage(data: data) 
      return userProfilePic 
     } 


    }) 
    return nil 
} 

답변

1

코드를 오류 여기 cannot convert the expressions type UIImage to type void swift

입니다 점점 ​​지키는 response, data하고, error 개체가 있지만 completionHandler 자체는 값을 반환하지 않을 것으로 예상합니다. 그러나 당신은 그 completionHandler 클로저에서 값을 반환하려고합니다.

결론적으로 비동기 방식 (즉, 함수에서 즉시 복귀하더라도 데이터가 나중에 반환 됨)을 수행 중이므로 함수에서 UIImage을 반환 할 수 없습니다.

func downloadFBUserImage(object: PFObject?, completionHandler: (UIImage?, NSError?) -> Void) { 
    if let userProfilePhotoURLString = object?.valueForKey("pictureURL") as? String { 
     let pictureURL = NSURL(string: userProfilePhotoURLString)! 
     let urlRequest = NSURLRequest(URL: pictureURL) 
     NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in 
      if data != nil { 
       var userProfilePic = UIImage(data: data) 
       completionHandler(userProfilePic, nil) 
      } else { 
       completionHandler(nil, error) 
      }  
     } 
    } 
} 

을 그리고 당신은 sendAsynchronousRequest가하는 것과 같은 완료 핸들러 패턴을 사용하여 호출 것 : 그래서, 비동기 패턴을 사용하면 그런 완료 블록으로 돌아갈 수 없습니다

downloadFBUserImage(object) { image, error in 
    if image == nil { 
     println(error) 
    } else { 
     // use the image here 
    } 
} 

// but don't try to use asynchronously retrieved image here 
+0

처럼 호출 할 수 있습니다! 필자는 항상 완성 핸들러가 함수 내에 있기 때문에 값을 반환 할 수도 있다고 생각했습니다. 그걸 정리 해줘서 고마워! – user3413380

0

. 완료 블록에 return 매개 변수가 없습니다. 이것이 오류를 일으키는 이유입니다.

다운로드 후 이미지를 업데이트하려면 다음과 같이 블록 downloadFBUserImage과 함께 전달할 수 있습니다.

메인 스레드에서 UI 업데이트를 수행해야하므로 dispatch_async을 사용했습니다.

func downloadFBUserImage(object: PFObject?, completion completionBlock:(UIImage) ->()) ->(){ 
    var userProfilePhotoURLString = object?.valueForKey("pictureURL") as String? 
    if userProfilePhotoURLString != nil { 
     var pictureURL: NSURL = NSURL(string: userProfilePhotoURLString!)! 
     var urlRequest: NSURLRequest = NSURLRequest(URL: pictureURL) 
     NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (NSURLResponse response, NSData data, NSError error) -> Void in 
      if error == nil && data != nil { 
       if let userProfilePic = UIImage(data: data) { 
        completionBlock(userProfilePic) 
       } 
      } 
     }) 
    } 
} 

괜찮아 아이

func do() { 
    downloadFBUserImage(pfObject, completion: { (image) ->() in 
      //updateImage 
      dispatch_async(dispatch_get_main_queue(), {() -> Void in 
       // UI updates 
      } 
    }) 
} 
관련 문제