2017-10-17 1 views
0

alamofire 변수에서 전역 변수를 변경하려고하는데 문제가 있습니다. 내가 적절한 데이터를 얻을 HttpRequest를 함수 내부를 인쇄하지만 때, 내가 여기 self.projects를 인쇄 할 때함수 내에서 전역 변수를 변경할 수 없습니다.

var projects = [[String]]() 
var xmlToParse = String() 
var postTitle = String() 
var postLink = String() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    httpRequest("https://www.hello.com/feed") { response in 
     self.xmlToParse = response as String 
     let xml = SWXMLHash.parse(self.xmlToParse) 

     for elem in xml["rss"]["channel"]["item"].all { 
      self.postTitle = elem["title"].element!.text 
      self.postLink = elem["link"].element!.text     
      self.projects.append([self.postTitle, self.postLink]) 
     } 
    } 
    print(self.projects) 
} 

, 난 빈 상태 (empty)의 배열이 : 여기 내 코드입니다. for 루프 내에서 전역 변수 프로젝트를 설정하지 않습니까? 함수 밖의 값을 어떻게 얻을 수 있습니까? 나는 아무 것도 성공하지 못하여 찾은 모든 것을 시도했다. 어떤 도움이라도 대단히 감사합니다.

그냥 추가 정보를 원하시면, 여기 내 HttpRequest에 함수이다 :

func httpRequest(_ section: String, completion: @escaping (String) -> Void) { 
    Alamofire.request(section, method: .get).responseString { response in 
     completion(response.result.value!) 
    } 
} 
+2

httpRequest 함수가 완료 핸들러를 호출하기 전에도 self.projects를 인쇄하기 때문입니다. – koropok

+0

흠 .. 그럼 어떻게하면 프로젝트 배열에 ViewDidLoad에서 적절한 함수를 사용하여 다른 함수에서도 액세스 할 수 있습니다. –

+0

논리를 완성 처리기에 배치하는 것이 왜 좋은가요? – koropok

답변

1

[ "채널"] [ "항목"] nil이 아닌 [ "RSS"] 그 XML을 가정 ...

override func viewDidLoad() { 
    super.viewDidLoad() 

    httpRequest("https://www.hello.com/feed") { response in 
     self.xmlToParse = response as String 
     let xml = SWXMLHash.parse(self.xmlToParse) 

     for elem in xml["rss"]["channel"]["item"].all { 
      self.postTitle = elem["title"].element!.text 
      self.postLink = elem["link"].element!.text     
      self.projects.append([self.postTitle, self.postLink]) 
     } 

     self.setup() 
    } 
} 

func setup() { 
    // Your logic here 
} 
+0

감사합니다. 그래도 설치 과정에서 혼란 스럽습니다. 원래 함수 httpRequest? –

+0

또, 내가하고있는 다음 일은 무 처리 에러 일 것이다. –

+0

setup 내에서 self.projects로 할 계획에 코드를 넣을 수있다. 이렇게하면 self.projects 변수에 이미 값이 지정되어 있는지 확인할 수 있습니다. – koropok

관련 문제