如何在Swift中调用Web服务?

时间:2014-06-16 00:32:03

标签: web-services swift

如何在Swift中调用RESTful Web服务?在Objective C中,我使用了以下代码,但未能找到有关如何在swift中执行相同操作的详细信息。

- (IBAction)fetchData;
{
NSURL *url = [NSURL URLWithString:@"http://myrestservice"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response,
                                           NSData *data, NSError *connectionError)
 {
     if (data.length > 0 && connectionError == nil)
     {
         NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:NULL];
         self.content.text = [[response objectForKey:@"text"] stringValue];
     }
 }];

}

5 个答案:

答案 0 :(得分:10)

好吧,如果您只想从Objective-C代码直接转换为Swift,它看起来就像下面的内容。但是,您可能希望观看并阅读上面的链接,以了解如何在Swift中更好地编写此代码。

    let url = NSURL(string: "http://myrestservice")
    let theRequest = NSURLRequest(URL: url)

    NSURLConnection.sendAsynchronousRequest(theRequest, queue: nil, completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        if data.length > 0 && error == nil {
            let response : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.fromMask(0), error: nil)
        }
    })

答案 1 :(得分:2)

使用Swift 2.0并将目标设置为iOS 8.0,您可以尝试:

override func viewDidLoad() {
    super.viewDidLoad()

  //Making Connection
   let urlPath = "https://EXAMPLE.com/json?Name=xxx&Emailid=xxx&password=xxx"       
   let url1: NSURL = NSURL(string: urlPath as String)!
   let request: NSURLRequest = NSURLRequest(URL: url1)
   let connection:NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
            connection.start()
}

//Connection Delegates
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){ 
   self.data?.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!)
{
   var error: NSErrorPointer=nil
   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
   print(jsonResult)

   var returnedString : NSString = jsonResult.valueForKey("keyName") as NSString
   print(returnedString)
}

答案 2 :(得分:1)

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="ctrl1">
    Hello, {{name}}!
  </div>
  <div ng-controller="ctrl2">
    My name is, {{name}}!
  </div>
</div>

答案 3 :(得分:1)

对于Swift 3.1

func callService ( urlString : String, httpMethod: String , data: Data , completion: @escaping (_ result: [String:AnyObject]) -> Void)
{

    let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL)
    // Set the method to POST
    request.httpMethod = httpMethod
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    // Set the POST/put body for the request
     request.httpBody = data
     request.setValue(String.init(format: "%i", (data.count)), forHTTPHeaderField: "Content-Length")

    let session = URLSession.shared

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        if data == nil
        {
            var errorResponse = [String : AnyObject]()
            errorResponse["Error"] = "Issue" as AnyObject?
            completion(errorResponse)
        }
        else
        {
        if  let utf8Text = String(data: data! , encoding: .utf8) {
                completion(self.convertStringToDictionary(text: utf8Text)! as! [String : AnyObject])
        }
        else
        {
            var errorResponse = [String : AnyObject]()
            errorResponse["Error"] = "Issue" as AnyObject?
            completion(errorResponse)
            }
        }
    })
    task.resume()
}

func convertStringToDictionary(text: String) -> NSDictionary? {
    if let data = text.data(using: String.Encoding.utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary as! [String : AnyObject]? as NSDictionary?
        } catch let error as NSError {
            var errorResponse = [String : AnyObject]()
            errorResponse["Error"] = "Issue" as AnyObject?
            print(error)
            return errorResponse as NSDictionary?
        }
    }
    return nil
}

使用上述功能从Web服务调用数据。

在任何方法中使用以下代码从任何服务调用中获取数据。

 let urlString = "Url String"
    var data = Data()
    do{
        let finalDict  = NSMutableDictionary()
       // finalDict.setValue(infoValue, forKey: "info")

        finalDict.setValue("------", forKey: "Token")

        let newdata = try JSONSerialization.data(withJSONObject:finalDict , options: [])
        let newdataString = String(data: newdata, encoding: String.Encoding.utf8)!
        print(newdataString)

        data = newdataString.data(using: .utf8)!

         let another =     try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary as! [String : AnyObject]? as NSDictionary?
        print(another!)

    }
    catch let error as NSError {
        print(error)
    }

    self.callService(urlString: urlString, httpMethod: "POST", data: data) { (response) in
        let mainData = response["meta"] as! NSDictionary
        var code = Int()
        code = mainData["code"]  as! Int
        if code != 200
        {
            var errorResponse = [String : AnyObject]()
            errorResponse["Error"] = "Issue" as AnyObject?
            completion(errorResponse)
        }
        else
        {
            completion(response)
        }
    }

希望这会有所帮助。

答案 4 :(得分:1)

导入UIKit

类ApidemoViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {

var Arrfetchdata = Array<Any>()


@IBOutlet weak var tblApi: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()

    let nib = UINib(nibName: "APIdemoTableViewCell", bundle: nil)
    tblApi.register(nib, forCellReuseIdentifier: "APIdemoTableViewCell")
    jsondata()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func jsondata()  {
    let url = URL(string : "http://www.exapmleurl.com")
    var request = URLRequest(url: url!)
    request.httpMethod="GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
    let task = session.dataTask(with: request)
    { (Data,URLResponse,Error) in

        if(Error != nil)
        {
            print("Error")
        }
        else{
            do{
               self.Arrfetchdata = try JSONSerialization.jsonObject(with: Data!, options: .mutableLeaves) as! Array<Any>



                for eachdata in self.Arrfetchdata
                {
                    let alldata = eachdata as! NSDictionary
                    let id = alldata["id"] as! String
                    let urlshow = alldata["url"] as! String
                    let name = alldata["name"] as! String
                    let image = alldata["image"]
                    let isActive = alldata["isActive"] as! String

                    print(alldata)
                    print(id)
                    print(urlshow)
                    print(name)
                    print(image)
                    print(isActive)
                }


            }


            catch{
                print("Error")
            }

            self.tblApi.reloadData()
        }
    }
    task.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Arrfetchdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "APIdemoTableViewCell", for: indexPath)as! APIdemoTableViewCell

      let dictindex1 : NSDictionary = Arrfetchdata[indexPath.row] as! NSDictionary
      let strid :NSString = dictindex1["id"]! as! NSString
      let strurl :NSString = dictindex1["url"]! as! NSString
      let strname :NSString = dictindex1["name"]! as! NSString
    if let booleanValue = dictindex1["image"] as? Bool {

        let strbool = String(booleanValue)
        cell.lblapiimage.text = strbool
    }
    else
    {
        let strimage :NSString = dictindex1["image"]! as! NSString
        cell.lblapiimage.text = strimage as String
    }
     /// let strimage :Bool = dictindex1["image"]! as! Bool
     let strisActive :NSString = dictindex1["isActive"]! as! NSString
      cell.lblapiid.text = strid as String
      cell.lblapiurl.text = strurl as String
    cell.lblapiname.text = strname as String
    // cell.lblapiimage.text = strimage as Bool
    cell.lblapiisActive.text = strisActive as String
      return cell

}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let gosubcategory = SubcategoryAPIViewController(nibName: "SubcategoryAPIViewController", bundle: nil)
    let dicsubcat:NSDictionary=Arrfetchdata[indexPath.row] as! NSDictionary
    gosubcategory.ArrSubcategory=dicsubcat.object(forKey:"subcategory") as! NSArray
    navigationController?.pushViewController(gosubcategory, animated: true)
}

}