Evo*_*net 0 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];
}
}];
Run Code Online (Sandbox Code Playgroud)
}
Enr*_*tyo 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)
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45458 次 |
| 最近记录: |