2016-12-25 63 views
0

我嘗試了Gurdev建議的完成處理程序並獲得了一些信息。它確實在MAIN函數中返回數組的值。但問題是一樣的:我必須使用Sleep()函數3秒來完成HTTP請求。這就像硬編碼,因爲它可能需要少於或超過3秒才能完成。當我刪除Sleep()命令時,最終返回一個VOID數組。訪問給定函數之外的變量

相關代碼如下。

謝謝!

--------Web Class-------- 
    import Foundation 
    import UIKit 

    class Web { 

     var ar1 = [Double]() 

     var ar2 = [Double]() 

     func getData(str: String, completion: (_ result: [[Double]]) -> Void) { 

    let request = NSMutableURLRequest(url: URL(string: str)!) 

    httpGet(request as URLRequest!){ 
     (data, error) -> Void in 
     if error != nil { 
      print(error ?? "Error") 
     } else { 
      let delimiter = "\t" 
      let lines:[String] = data.components(separatedBy: CharacterSet.newlines) as [String] 

     for line in lines { 
       var values:[String] = [] 
       if line != "" { 
        values = line.components(separatedBy: delimiter) 
        let str1 = (values[0])//FIRST COLUMN 
        let str2 = (values[1])//SECOND COLUMN 
        let db1 = NumberFormatter().number(from: str1)?.doubleValue 
        self.ar1.append(db1!) 
        let db2 = NumberFormatter().number(from: str2)?.doubleValue 
        self.ar2.append(db2!) 

       } 

      } 

     } 

    }//end of request 

    sleep(3) // This delay sends data to MAIN, Otherwise NOT 

    let dta = [self.ar1, self.ar2] 

    completion(dta) 

    } 

    func httpGet(_ request: URLRequest!, callback: @escaping (String, String?) -> Void) { 
    let session = URLSession.shared 
    let task = session.dataTask(with: request, completionHandler: { 
     (data, response, error) -> Void in 
     if error != nil { 
      callback("", error!.localizedDescription) 
     } else { 
      let result = NSString(data: data!, encoding: 
       String.Encoding.ascii.rawValue)! 
      callback(result as String, nil) 
     } 
     }) 
     task.resume() 
    } 

} 網站-------- --------類

-------Call In Class-------- 
Web().getData (str: "https://dl.dropboxusercontent.com/s/f6j7w7zeqaavzqw/s02.txt?dl=0") 
     { 
     (result: [[Double]]) in 

      let x = result[0] 
      let y = result[1] 
} 
-------Call In Class-------- 

從本質上講,我想在某一個點來訪問我的變量 「AR1」在我的代碼中,但我不能。我試圖返回值,但它在那一點上返回NULL。

這裏有什麼問題?

我試圖像下面的代碼:

import Foundation 
import UIKit 

class Web { 
    var ar1 = [Double]() 
    var ar2 = [Double]() 

    func getData(str: String) -> [Double] { 
    let request = NSMutableURLRequest(url: URL(string: str)!) 
     httpGet(request as URLRequest!){ 
      (data, error) -> Void in 
      if error != nil { 
       print(error ?? "Error") 
      } else { 
       let delimiter = "\t" 
       let lines:[String] = data.components(separatedBy:  CharacterSet.newlines) as [String] 

       for line in lines {   
        var values:[String] = [] 
        if line != "" { 
         values = line.components(separatedBy: delimiter) 
         let str1 = (values[0])//FIRST COLUMN 
         let str2 = (values[1])//SECOND COLUMN 
         let db1 = NumberFormatter().number(from: str1)?.doubleValue 
         self.ar1.append(db1!) 
         let db2 = NumberFormatter().number(from: str2)?.doubleValue 
         self.ar2.append(db2!) 
        } 
       } 
      dump (self.ar1) // "ar1" accessible HERE (returns all elements) 
     } 
    }//end of request 
     //BUT I WANT TO RETURN "ar1" HERE ! 
     // So that I can use it in my MAIN class 
     dump (self.ar1) // "ar1" not accessible here (returns ZERO elements) 
     return self.ar1 
    } 
     func httpGet(_ request: URLRequest!, callback: @escaping (String, String?) -> Void) { 
      let session = URLSession.shared 
      let task = session.dataTask(with: request, completionHandler: { 
       (data, response, error) -> Void in 
       if error != nil { 
       callback("", error!.localizedDescription) 
       } else { 
       let result = NSString(data: data!, encoding: 
        String.Encoding.ascii.rawValue)! 
       callback(result as String, nil) 
       } 
      }) 
      task.resume() 
} 
    } 
+0

您可能無法使用受版權保護的內容並保留在StackOverflow上的所有權利。請參閱http://stackoverflow.com/help/licensing –

回答

2

在你的代碼是從你的方法的返回語句,返回ar1而價值ar1在Aysnchronous回調完成處理程序被設置。您應該使用您嘗試訪問ar1的值的完成處理程序塊。 HTTPGet函數以異步模式運行,ar1中的值在回調處理程序塊中設置。

讓我知道你是否需要任何進一步的幫助。

+1

當HTTP請求仍在接收來自服務器的響應時,您的返回語句提前返回值。您需要更改函數getData,以便它使用完成處理程序塊。您還需要更改當前調用'getData'的代碼,以便在完成處理程序回調中編寫使用'ar1'的值的邏輯。 https://thatthinginswift.com/completion-handlers/ –