2017-08-31 47 views
-2

我對封閉不是很熟悉。我使用這個功能從遠程服務器向封閉添加返回值

requestJson(){ 
    // Asynchronous Http call to your api url, using NSURLSession: 
    NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://api.site.com/json")!, completionHandler: { (data, response, error) -> Void in 
     // Check if data was received successfully 
     if error == nil && data != nil { 
      do { 
       // Convert NSData to Dictionary where keys are of type String, and values are of any type 
       let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject] 
       // Access specific key with value of type String 
       let str = json["key"] as! String 
      } catch { 
       // Something went wrong 
      } 
     } 
    }).resume() 
} 

下載一個JSON文件是否有可能使功能requestJson()時,其裝回JSON文件?或者這是不可能的,因爲它是異步加載的並且無法做好準備?想讓我試圖做的是類似以下內容:

requestJson() -> **[String : AnyObject]**{ 
    // Asynchronous Http call to your api url, using NSURLSession: 
    NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://api.site.com/json")!, completionHandler: { (data, response, error) -> Void in 
     // Check if data was received successfully 
     if error == nil && data != nil { 
      do { 
       // Convert NSData to Dictionary where keys are of type String, and values are of any type 
       let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject] 
       // Access specific key with value of type String 
       **return json** 
      } catch { 
       // Something went wrong 
      } 
     } 
    }).resume() 
} 
+2

使用completionhandlers /回調從發送數據的內部封閉 – 3stud1ant3

+0

的創建/自己實現自己封閉你自己的方法'requestJson()'。 – Larme

+0

您可以在閉包中返回值作爲完成處理程序。 – Jaydeep

回答

1

,您可以給函數PARAMS的@escaping回調返回一個數組或任何你需要的;

這是一個網絡請求的例子;

class func getGenres(completionHandler: @escaping (genres: NSArray) ->()) { 
... 
let task = session.dataTask(with:url) { 
    data, response, error in 
    ... 
    resultsArray = results 
    completionHandler(genres: resultsArray) 
} 
... 
task.resume() 
} 

然後打電話給你,你可以做這樣的事情;

override func viewDidLoad() { 
    getGenres { 
     genres in 
     print("View Controller: \(genres)")  
    } 
} 
-1
func httpGet(request: NSURLRequest!, callback: (NSString, NSString?) -> Void) 
{ 
var session = NSURLSession.sharedSession() 
var task = session.dataTaskWithRequest(request){ 
    (data, response, error) -> Void in 
    if error != nil { 
     callback("", error.localizedDescription) 
    } else { 
     var result = NSString(data: data, encoding: 
      NSASCIIStringEncoding)! 
     callback(result, nil) 
    } 
} 
task.resume() 

} 

func makeRequest(callback: (NSString) ->Void) -> Void { 

var request = NSMutableURLRequest(URL: NSURL(string: "http://sample_url")!) 

var result:NSString = "" 


httpGet(request){ 
    (data, error) -> Void in 

    if error != nil { 
     result = error! 
    } else { 
     result = data 
    } 


    callback(data) 
} 

} 

用法: -

self.makeRequest(){ 
    (data) -> Void in 
    println("response data:\(data)") 

} 
0
//MARK: Request method to get json 

class func requestJSON(completion: @escaping (returnModel: String?) -> Void) { 
      //here you write code for calling API 
    } 

//MARK: Calling function to retrieve return string 

API.requestJSON(completion: { (string) in 
     //here you can get your string 
    })