Search code examples
iosswiftdelegatesblockdelegation

iOS: pass data to another class


I have my class named "Service" where inside I do a lot of GET/POST request with Alamofire, an example of request id this

func requestDocuments(){

        request(.POST, "http://example.com/json/docs")
            .responseJSON { (_, _, JSON, error) in

                if error == nil{

                    var response = JSON as NSArray
                    println("array document: \(response)")


                    //**** HERE I WANT PASS VALUE TO MY VIEW CONTROLLER
                }
                else{

                }
        }
    }

and from my viewcontroller:

    let service = Service.sharedInstance

    service.requestDocuments()

What can I use? delegate method? or what? what is the best solution in swift?


Solution

  • func requestDocuments(completion:(data:NSArray?)){
    
            request(.POST, "http://example.com/json/docs")
                .responseJSON { (_, _, JSON, error) in
    
                    if error == nil{
    
                        var response = JSON as NSArray
                        println("array document: \(response)")
    
    
                        //**** HERE I WANT PASS VALUE TO MY VIEW CONTROLLER
    
                        completion(data:response)
                    }
                    else{
                       completion(data:nil)
                    }
            }
        }
    
    
    
     var reqDoc = requestDocuments(){ (data) -> Void in 
          if let _data = data {
             dispatch_async(dispatch_get_main_queue()) {
             //Do something with data
             }
          }
    
    }
    

    I think closures is the best solution.