我怎么得到另一个视图控制器中的ios swift json返回函数值

时间:2016-10-24 10:23:01

标签: ios swift3

  func data_request(){
  let url:NSURL = NSURL(string: url_to_request)!
  let session = URLSession.shared
  let request = NSMutableURLRequest(url: url as URL)
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
//let paramString = "data=Hello"
let paramStrings = paramString
request.httpBody = paramStrings.data(using: String.Encoding.utf8)
  let task = session.dataTask(with: request as URLRequest) { ( data,   response, error) in
    guard let :NSData = data as NSData?, let :URLResponse = response , error   == nil else {
        // print("error") //
        return //
    }
    let dataString = NSString(data: data!, encoding:          String.Encoding.utf8.rawValue)
    print(dataString)


};

  task.resume()

}

如何在另一个视图中获取返回值datastring?我如何通过这个价值..在ios..plshelp的初学者....提前感谢

1 个答案:

答案 0 :(得分:0)

使用阻止你可以做到这一点

对于斯威夫特。将AnyObject用于id objc类型。

func callWebservice (serviceName: String, withMethod method: String, andParams params: NSDictionary, showLoader loader: Bool, completionBlockSuccess aBlock: ((AnyObject) -> Void), andFailureBlock failBlock: ((AnyObject) -> Void)) {
    if loader {
        // Show loader
    }

    performRequestWithServiceName(serviceName, method: method, andParams: params, success: aBlock, failure: failBlock)
}

func performRequestWithServiceName(serviceName: String, method methodName: String, andParams params: NSDictionary, success successBlock: ((AnyObject) -> Void), failure failureBlock: ((AnyObject) -> Void)) {
    if callSuceess {
        successBlock("Success")
    }else {
        successBlock(nil)
    }
}

您需要致电web service的示例。见下面的代码

callWebservice("your-service-name", withMethod: "your-method", andParams: ["your-dic-key": "your dict value"], showLoader: true/*or false*/, completionBlockSuccess: { (success) -> Void in
    // your successful handle
}) { (failure) -> Void in
    // your failure handle
}

来自:https://stackoverflow.com/a/31491077/3901620