基本的网络请求
1 2 3 4 5 6 7 8
| let url = NSURL(string: "http://imba97.cn/wp-json/wp/v2/posts/491") NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, _, _) -> Void in NSJSONSerialization.JSONObjectWithData(data!, options: [NSJSONReadingOptions.MutableContainers, NSJSONReadingOptions.MutableLeaves]) }.resume()
|
JSONObjectWithData
的options
选项,OC中的按位枚举的方式改为数组的方式设置,如果不设置选项可以直接设为空数组[]
封装网络方法
使用AFNetworking
框架进行二次封装,首先使用Cocoapods加载第三方框架
NetworkTools.swift
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import UIKit import AFNetworking
enum requestMethod: String { case GET = "GET" case POST = "POST" }
class NetworkTools: AFHTTPSessionManager { static let sharedTools: NetworkTools = { let tools = NetworkTools(baseURL: nil) tools.responseSerializer.acceptableContentTypes?.insert("text/html") return tools }() }
extension NetworkTools { func request(method: requestMethod, URLString: String, parameters: [String: Any]?, finished: (result: Any?, error: NSError?)->()) { let success = { (task: NSURLSessionDataTask, result: Any) -> Void in finished(result: result, error: nil) } let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in print(error) finished(result: nil, error: error) } if method == requestMethod.GET { GET(URLString, parameters: parameters, success: success, failure: failure) } else { POST(URLString, parameters: parameters, success: success, failure: failure) } } }
|
调用,ViewController.swift
文件
1 2 3 4 5 6 7 8 9
| import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NetworkTools.sharedTools.request(requestMethod.GET, URLString: "http://imba97.cn/wp-json/wp/v2/posts/491", parameters: nil) { (result, error) -> () in print(result) } } }
|