Web services 如何在Swift中调用Web服务?
如何在Swift中调用RESTful web服务?在Objective C中,我使用了以下代码,但还没有找到在swift中如何执行相同操作的详细信息Web services 如何在Swift中调用Web服务?,web-services,swift,Web Services,Swift,如何在Swift中调用RESTful web服务?在Objective C中,我使用了以下代码,但还没有找到在swift中如何执行相同操作的详细信息 - (IBAction)fetchData; { NSURL *url = [NSURL URLWithString:@"http://myrestservice"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchrono
- (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];
}
}];
}如果您只想直接从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)
}
})
使用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)
}
对于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)
}
}
希望这会有所帮助。导入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)
}
var Arrfetchdata=Array()
@IBVAR tblApi:UITableView!
重写func viewDidLoad(){
super.viewDidLoad()
让nib=UINib(nibName:“APIDomableViewCell”,bundle:nil)
tblApi.register(nib,强制重用标识符:“APIDomableViewCell”)
jsondata()
//加载视图后执行任何其他设置。
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
func jsondata(){
让url=url(字符串:http://www.exapmleurl.com")
var request=URLRequest(url:url!)
request.httpMethod=“GET”
let configuration=URLSessionConfiguration.default
let session=URLSession(配置:配置,委托:nil,delegateQueue:OperationQueue.main)
let task=session.dataTask(带:request)
{(数据、URL响应、错误)在
如果(错误!=nil)
{
打印(“错误”)
}
否则{
做{
self.Arrfetchdata=try JSONSerialization.jsonObject(使用:Data!,选项:.mutableLeaves)作为!数组
对于self.Arrfetchdata中的每个数据
{
让alldata=eachdata为!NSDictionary
设id=alldata[“id”]为!字符串
让urlshow=alldata[“url”]作为!字符串
让name=alldata[“name”]作为!字符串
让image=alldata[“image”]
让isActive=alldata[“isActive”]作为!字符串
打印(所有数据)
打印(id)
打印(urlshow)
印刷品(名称)
打印(图像)
打印(isActive)
}
}
抓住{
打印(“错误”)
}
self.tblApi.reloadData()
}
}
task.resume()
}
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
返回Arrfetchdata.count
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
让cell=tableView.dequeueReusableCell(标识符为:“APIdemoTableViewCell”,for:indexPath)作为!APIdemoTableViewCell
让dictindex1:NSDictionary=Arrfetchdata[indexath.row]作为!NSDictionary
让strid:NSString=dictindex1[“id”]!as!NSString
让strurl:NSString=dictindex1[“url”]!as!NSString
让strname:NSString=dictindex1[“name”]!as!NSString
如果让booleanValue=dictindex1[“图像”]作为?Bool{
设strbool=String(布尔值)
cell.lblapiimage.text=strbool
}
其他的
{
让strimage:NSString=dictindex1[“image”]!as!NSString
cell.lblapiimage.text=strimage为字符串
}
///让strimage:Bool=dictindex1[“image”]!as!Bool
让strisActive:NSString=dictindex1[“isActive”]!as!NSString
cell.lblapiid.text=strid作为字符串
cell.lblapiurl.text=strurl作为字符串
cell.lblapiname.text=字符串形式的strname
//cell.lblapiimage.text=strimage为Bool
cell.lblapiisActive.text=strisActive作为字符串
返回单元
}
func tableView(tableView:UITableView,didSelectRowAt indexPath:indexPath){
让gosubcategory=SubCategory APIViewController(nibName:“SubCategory APIViewController”,bundle:nil)
让dicsubcat:NSDictionary=Arrfetchdata[indexPath.row]作为!NSDictionary
gosubcategory.ArrSubcategory=dicsubcat.object(forKey:“subcategory”)作为!NSArray
navigationController?.pushViewController(gosubcategory,动画:true)
}
}我实际上不知道从哪里开始,因为我还在学习Swift——希望有人能给我指点教程或一些关于寻找什么的指点!我建议您阅读本书的全部或至少部分内容,也可能阅读本书。还有3个视频可用:,这个问题似乎离题了,因为它没有显示出对正在解决的问题的最低理解,这些书为swift的语法以及如何将objective-c代码转换为swift提供了一个起点。我们不能一个接一个地为人们手工转换代码。我非常愿意帮助处理错误当人们试图转换它时,如果队列为nil则无法工作,您必须将队列指定为NSOperationQueue.mainQueue(),以便处理错误,完成处理程序的数据和错误参数都必须是可选的包装。即更改数据:NSData!到数据:NSData?如何获取检索到的数据?例如,如果web服务返回一个字符串,如何获取该字符串?
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)
}