I am new to Swift
iOS and i want to create a separate method in separate class(like NSObject
) of web services so that i can use it in any ViewController and parse any type of JSON
response using NSURLSession
and Alamofire
. Could someone help me.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
class WebRequester: NSObject {
static let shared = WebRequester()
let session = URLSession.shared
func request(urlStr:String, parameter:String, token:String? = nil, callback:@escaping (_ result:NSDictionary?, error:Error?) -> Void) {
let url = URL(string: BaseURL + urlStr)
debugPrint("=====================")
debugPrint(url ?? "")
debugPrint(parameter)
debugPrint("=====================")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = parameter.data(using: String.Encoding.utf8)
print("Token :", (token ?? ""))
request.setValue(token, forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
if error == nil {
do {
let jsonObj = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
if let dic = jsonObj as? NSDictionary {
callback(dic, error)
}
}
catch {
callback(nil, error)
}
}
else {
callback(nil, error)
}
}
}
task.resume()
}
}
You need to pass parameter as string
var params = "user_id=" + "12"
params += "&course_id=" + "1"
WebRequester.shared.request(urlStr: urlStr, parameter: params) { (result, error) in
DispatchQueue.main.async {
print(result)
}
}
you can also pass parameter as dictionary but need to convert in string using following Dictionary
extension
request.httpBody = parameter.stringFromHttpParameters().data(using: String.Encoding.utf8)
extension Dictionary {
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let percentEscapedValue = (value as AnyObject).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joined(separator: "&")
}
}
WebRequester
- Http Request
- multipart with single image
- multipart with multiple image
You need to change response structure as per your api response
you need to set authorisation and api key as per your api
WebRequester
回答2:
Here is a working code of Alamofire (swift 4)
Add this class in your project
import Foundation
import UIKit
import Alamofire
import SystemConfiguration
class APPWebService: NSObject {
class open func callPostApi(api:String, parameters:[String:AnyObject]?, complition:@escaping (AnyObject)->Void)
{
if self.IsInternetAvailable() == false {
self.showAlert(title: "Whoops :(", message: "No internet connection.")
return
}
let parameters = parameters
// Encode Data
let base64EncodedString = toBase64EncodedString(toJsonString(parameters: parameters!))
Alamofire.request(api, method: .post, parameters: ["jsondata":base64EncodedString])
.response { response in
do {
if response.error != nil{
print(response.error as Any, terminator: "")
}
if let jsonDict = try JSONSerialization.jsonObject(with: (response.data as Data?)!, options: []) as? [String: AnyObject]{
print(jsonDict as Any, terminator: "")
complition(jsonDict as AnyObject)
}else{
self.showAlert(title: "Whoops", message: "Something went wrong. Please, try after sometime.")
return
}
} catch _ {
print("Exception!")
}
}
}
// For check Internet Connection
class open func IsInternetAvailable () -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
// Display Alert
class open func showAlert(title:String,message:String){
let alert = UIAlertView(title:title,message: "\n" + message,delegate: nil ,cancelButtonTitle: "Ok")
alert.show()
}
// For Convert to JSON String
class open func toJsonString(parameters:[String:AnyObject]) -> String
{
var jsonData: NSData?
do {
jsonData = try JSONSerialization.data(withJSONObject: parameters, options:JSONSerialization.WritingOptions(rawValue: 0)) as NSData?
} catch{
print(error.localizedDescription)
jsonData = nil
}
let jsonString = NSString(data: jsonData! as Data, encoding: String.Encoding.utf8.rawValue)! as String
return jsonString
}
// For Convert to Base64Encoded String
class open func toBase64EncodedString(_ jsonString : String) -> String
{
let utf8str = jsonString.data(using: .utf8)
let base64Encoded = utf8str?.base64EncodedString(options: [])
return base64Encoded!
}
}
Use Like this
func ServiceCall()
{
// Create parameter list
let parameters = [
"name":"Abc",
"address":"Xyz",
"contact":"1234567890"
]
// set webservice Url
let ReqURL = "your webservice url here"
APPWebService.callPostApi(api: ReqURL, parameters: parameters as [String : AnyObject]?) { (dict) -> Void in
print(dict) // Your response is here.
}
}