2015-01-12 3 views
3

내 프로젝트에서 데이터 요청 (JSON, 이미지 등)을 위해 네트워크 인터페이스를 처리하기위한 공용 클래스를 만들었습니다. 클래스 내부의 함수는 Alamofire를 사용하여 네트워크 연결을 설정하고 JSON 파일을 다운로드합니다.swift에서 클래스 함수에 콜백 추가하기

클래스와 기능은 다음과 같습니다 :

import Foundation 
import Alamofire 

public class DataConnectionManager { 

    public class func getJSON(AppModule:String, callback:(Int) -> Void) -> Void { 

     switch(AppModule) { 

     case "Newsfeed": 
      Alamofire.request(.GET, "http://some-site.com/api/", encoding: .JSON).responseJSON { (_, _, JSONData, _) in 
       if JSONData != nil { 
        jsonHolder.jsonData = JSONData! 
        print("start") 
        callback(1) 
       } 
       else { 
        callback(0) 
       } 
      } 
      break 

     default: 
      break 

     } 

    } 

} 

나는 내 프로젝트에서 함수를 호출 아래와 같이 :

DataConnectionManager.getJSON("Newsfeed", callback: { (intCheck : Int) -> Void in 
    if intCheck == 1 { 
     println("Success") 
    } 
    else { 
     println("Failure") 
    } 
}) 
앱에서 오류없이 실행됩니다

는, 그러나 내 정신이 돈을 확인 출력하지 마라. 사실, 이렇게하면 Alamofire.request는 JSON 피드를 가져 오지 않습니다.

나는 이것을 올바른 방향으로 향하고 있습니까?

+0

디버깅 해 보셨습니까? 뉴스 피드에 갔습니까? –

+1

스타일의 문제처럼, 변수 이름에는 대문자를 사용하지 마십시오. 'JSONData'는 타입처럼 보이지만,'jsonData'는 변수처럼 보입니다. 두문자어로 시작하는 변수의 경우 약간 모호하지만, 대부분의 언어보다 스위프트는 모든 유형이 대문자이고 모든 변수가 소문자입니다. – SelectricSimian

+0

당신은'responseJSON'으로부터 에러를 버리고 있습니다. 그것을 ('_, _, JSONData, error)''if error! = nil' 대신 파싱 해보십시오. –

답변

1

나는이 방법을 사용할 수있게되었지만, 정확히 어떻게 확신 할 수는 없습니다. 사용자 제안 (오류 검사 추가 등)을 기반으로 몇 가지를 변경했으며 마술처럼 작동하기 시작했습니다. 여기 내 업데이트 된 코드를 사람들이 자신의 기능에 콜백을 추가하는 방법을 볼 수 있습니다.

내 "은 ConnectionManager"

import Foundation 
import Alamofire 

public class DataConnectionManager { 

    public class func getJSON(AppModule:String, callback:(Int) -> Void) -> Void { 

     switch(AppModule) { 

     case "Newsfeed": 
      Alamofire.request(.GET, "http://some-site.com/api/", encoding: .JSON).responseJSON { (_, _, alamoResponse, error) in 
       if (error != nil){ 
        println("You've got a response error!") 
        callback(0) 
       } 
       else { 
        if alamoResponse != nil { 
         jsonHolder.jsonData = alamoResponse! 
         callback(1) 
        } 
        else { 
         println("You've got some random error") 
         callback(0) 
        } 
       } 
      } 
      break 

     default: 
      break 

     } 

    } 

} 

함수에 내 전화 :

DataConnectionManager.getJSON("Newsfeed", callback: { (intCheck : Int) -> Void in 
    if intCheck == 1 { 
     self.createTable() 
    } 
    else { 
     println("Failure") 
    } 
}) 
1
나는 빠른 2.0 + SwiftyJSON을 사용하고

이이 구현하는 내 코드입니다 :

class func getJSON(AppModule:String, urlToRequest: String, resultJSON:(JSON) -> Void) -> Void { 
    var returnResult: JSON = JSON.nullJSON 

    switch(AppModule) { 
    case "all": 
     request(.GET, urlToRequest) 
      .responseJSON { (_, _, result) in 
      if (result.isFailure){ 
       print("You've got a response error!") 
       resultJSON(nil) 
      } 
      else { 
       if (JSON(result.value!) != nil) { 
        returnResult = JSON(result.value!) 
        resultJSON(returnResult) 
       } 
       else { 
        print("You've got some random error") 
       } 
      } 
     } 
     break 

    default: 
     break 

    } 

} 

다음과 같이 함수를 호출하십시오.

DataManager.getJSON("all",urlToRequest: "myurl.com", resultJSON: { (result: JSON) -> Void in 
     if (result == nil){ 
      // error with result json == nil 
      return 
     }else{ 
      //do something with json result 
     } 
    }) 

희망이 있으면 도움이 될 것입니다.

관련 문제