Alamofire request is not executed in swift 5 - ios

I have been using Alamofire in my whole project. Now in one of my modules, the Alamofire.request() is not getting executed. I tried putting a breakpoint and it showed that all of a sudden the request is being skipped. As I am working on a live project for security purpose am not including the URL. The code which I used is given here.
func responseFunction() {
let url = ""
let parametervalue = ["enq_id" : self.enquiry_id]
print(self.enquiry_id)
Alamofire.request(url, method: .post, parameters: parametervalue).responseJSON(completionHandler: {response in
if let response_data = response.result.value as? NSDictionary{
let rdata = response_data.value(forKey: "response") as! String
if rdata == "Success"
{
let res_data = response_data.value(forKey: "result") as! [NSDictionary]
print(res_data)
for resultdata in res_data{
let enqid = resultdata.value(forKey: "enq_id") as! String
let userid = resultdata.value(forKey: "user_id") as! String
let reference_no = resultdata.value(forKey: "reference_no") as! String
let enq_date = resultdata.value(forKey: "enq_date") as! String
let enq_time1 = resultdata.value(forKey: "enq_time") as! String
let enq_time2 = enq_time1.replacingOccurrences(of: "+", with: " ")
let enq_time = enq_time2.replacingOccurrences(of: "%3A", with: " : ")
}
self.queryResponseTable.reloadData()
}
else{
let alertController = UIAlertController(title: "Response Details", message: "Server Error ! Could not get any response. Please try again later!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .default))
self.present(alertController, animated: true, completion: nil)
}
}
})
}
Can anyone help me out?

I think the below code helps you.
func Api_withParameters(aView : UIView, aWebServiceName : String, aDictParam : Dictionary<String, Any>, completeBlock: #escaping ( _ response: AnyObject) -> Void, errorBlock: #escaping ( _ error: AnyObject) -> Void) {
let passingURL = "\(BASEURL)/\(aWebServiceName)"
let jsonData = try? JSONSerialization.data(withJSONObject: aDictParam, options: [])
var jsonString = String(data: jsonData!, encoding: .utf8)
jsonString = jsonString!.filter { !"\\)(\n\t\r".contains($0) }
let passingParameter = [K_APIKEY:APIKEY, K_Data:jsonString!]
print("***** Web-Service URL : \(passingURL) \n Passing Parameter : \(passingParameter)")
Alamofire.request(passingURL, method: HTTPMethod.post, parameters: passingParameter, encoding: URLEncoding.default, headers: HEADER_CONTENT_TYPE).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
completeBlock(response.result.value as AnyObject)
break
case .failure(let error):
var errorDict = [String : Any]()
let errorcode : Int = error._code
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 404:
errorDict = ["errormsg" : "Invalid URL: \(passingURL)", "errorCode" : httpStatusCode]
default: break
}
} else {
if (String(errorcode) == "-1009"){
errorDict = ["errormsg" : "Please check your internet connection"]
}
else if(error.localizedDescription != ""){
errorDict = ["errormsg" : error.localizedDescription]
}
else{
errorDict = ["errormsg" : "Server unreachable please try again later."]
}
}
errorBlock(errorDict as AnyObject)
break
}
}
}

Related

Getting crash reported in crashlytics about partial apply for closure

I am getting a crash reported in firebase related with - partial apply for closure. I tried answers on SO but they mainly says about use of [Weak self], I used it but still getting crash report of same. However not facing crash on my device.
Snapshot of crash report is this:
Related code of Network Manager is this:
//MARK: POST Methods for API Calls
func postRequest(urlString: String,
params:[String : Any],
view:UIView,
token:String,
success:#escaping (SuccessHandler),
failure:#escaping (ErrorHandler)) {
showProgressView(in: view)
let url = self.baseURL.appendingPathComponent(urlString)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
if token != "" {
urlRequest.addValue("\(token)", forHTTPHeaderField: "token")
}
urlRequest.networkServiceType = .default
urlRequest.cachePolicy = .reloadRevalidatingCacheData
urlRequest.timeoutInterval = 100
urlRequest.httpShouldHandleCookies = true
urlRequest.httpShouldUsePipelining = false
urlRequest.allowsCellularAccess = true
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
}
catch let error as NSError {
print(error.localizedDescription)
}
let task = defaultSession.dataTask(with: urlRequest, completionHandler: { [weak self] (data, response, error) -> () in
self?.hideProgressView()
guard error == nil else {
failure(error!)
return
}
let statusCode = (response as? HTTPURLResponse)?.statusCode
if urlString.contains("signin") {
let token = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "token")
UserDefaults.standard.setValue(token, forKey: "authToken")
}
switch statusCode {
case 200:
if let aData = data {
do {
let responseJSON = try JSONSerialization.jsonObject(with: aData, options: [])
success(responseJSON) // Line no 160 mentioned in crash report
}
catch let error as NSError {
failure(error)
}
}
case 404:
if let aData = data {
do {
let responseJSON = try JSONSerialization.jsonObject(with: aData, options: [])
let dictObj = responseJSON as? [String: Any] ?? [String: Any]()
let message = dictObj["message"] ?? ""
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : message])
failure(error)
}
catch let error as NSError {
failure(error)
}
}
default:
self?.logger.error("New Http Response Code")
}
})
task.resume()
}
Login Class method from where this api call is invocated:
func loginAPICall() {
email = txtFieldUsername.text ?? ""
let password = txtFieldPassword.text ?? ""
let params = ["username" : email,"password":password]
NetworkManager.shared().postRequest(urlString: API.signIn, params: params, view: self.view, token: "") { (response) in
let arrObj = response as? [AnyObject] ?? [AnyObject]()
let dictObj = arrObj[0] as? [String: Any] ?? [String: Any]()
self.saveUserdata(dict: dictObj)
DispatchQueue.main.async {
let vc = self.storyboard?.instantiateViewController(identifier: ViewControllerIdentifier.ProfileLandingId) as! ProfileLandingVC
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
}
} failure: { (error) in
print("error")
}
}
Earlier i was not using [weak self], recently added after following some answers. Can someone suggest a solution for it?

Converting Graph API from Swift 3 to Swift 5 for Facebook SDK

I am developing an app that allows the user to login using Facebook. The code snippet I have is using Swift 3 though and I can't find a converter online. The Swift 3 code is as follows:
In the example which is in Swift 3, Xcode suggests:
request.start(completion: ((HTTPURLResponse?, GraphRequestResult<GraphRequest>) -> Void)?)
And the programmer then enters (this is the entire function):
func getUserInfo(completion: #escaping (_ : [String: Any]?, _ : Error?) -> Void) {
let request = GraphRequest(graphPath: "me", parameters: ["fields" : "id,email,picture"])
request.start { response, result in
switch result {
case .failed(let error):
completion(nil, error)
case .success (let graphResponse):
completion(graphResponse.dictionaryValue, nil)
}
}
When I start to type:
request.start
Which gives me this line of code:
request.start(completionHandler: GraphRequestBlock?)
How can I convert this from Swift 3 to Swift 5?
Update after comment
My "HomeAfterLogInViewController.swift" file is as follows:
import Foundation
import FacebookCore
import FacebookLogin
class HomeAfterLogInViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
getFacebookProfileInfo()
}
}
func getFacebookProfileInfo()
{
let requestMe = GraphRequest.init(graphPath: "me", parameters: ["fields" : "id,name,email,picture.type(large)"])
let connection = GraphRequestConnection()
connection.add(requestMe, completionHandler:{ (connectn, userresult, error) in
if let dictData: [String : Any] = userresult as? [String : Any]
{
DispatchQueue.main.async
{
if let pictureData: [String : Any] = dictData["picture"] as? [String : Any]
{
if let data : [String: Any] = pictureData["data"] as? [String: Any]
{
print(data)
print(dictData["email"]!)
}
}
}
}
})
connection.start()
}
And this code works but there is one more step I need - explained in the screenshot:
func getFacebookProfileInfo() {
let requestMe = GraphRequest.init(graphPath: "me", parameters: ["fields" : "id,name,email,picture.type(large)"])
let connection = GraphRequestConnection()
connection.add(requestMe, completionHandler: { (connectn, userresult, error) in
if let dictData: [String : Any] = userresult as? [String : Any] {
DispatchQueue.main.async {
if let pictureData: [String : Any] = dictData["picture"] as? [String : Any] {
if let data : [String: Any] = pictureData["data"] as? [String: Any] {
print(data)
print(dictData["email"]!)
}
}
}
}
})
connection.start()
}
Try the below code to get the information of the user.
let params = ["fields":"email, id, name, first_name, last_name,gender"]//, user_gender, user_birthday"]
let request = GraphRequest(graphPath: "me", parameters: params, accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
request.start { (response, result) in
switch result {
case .success(let value):
print(value.dictionaryValue!)
var parsedData = value.dictionaryValue as Dictionary<String, AnyObject>?
if let firstName = parsedData?["first_name"] {
print("First Name: \(firstName)")
}
if let lastName = parsedData?["last_name"] {
print("Last Name: \(lastName)")
}
if let email = parsedData?["email"] {
print("Email: \(email as! String)")
}
if let id = parsedData?["id"] {
let faceBookId = id as! String
print("Facebook Id: \(faceBookId)")
//you can get profile picture URL here.
let pictureURL = "https://graph.facebook.com/" + "\(faceBookId)/" + "picture?type=large&return_ssl_resources=1"
print("Profile Picture URL: \(pictureURL)")
}
case .failed(let error):
print(error.localizedDescription)
}
}
GraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if error == nil{
//everything works print the user data
if let userInfo = result as? [String: Any] {
if let email = userInfo["email"] as? String {
let firstName = userInfo["first_name"] as? String
let lastName = userInfo["last_name"] as? String
var profilePicUrl: String? = nil
if let fbUserId = userInfo["id"] as? String {
profilePicUrl = "http://graph.facebook.com/\(fbUserId)/picture?type=large"
}
//Do your operations here.
}
}
}
})
Hope that will help!

How Can i get Charge and how to pass token id to charge in swift (IOS)

How to generate stripe token id, charge id in swift. Please, could anyone help on the generation of stripe payment in swift?
First do stripe payment configuration
let configuration = STPPaymentConfiguration.shared()
configuration.additionalPaymentMethods = .all
configuration.appleMerchantIdentifier = "Your stripe identifier"
configuration.canDeletePaymentMethods = true
configuration.createCardSources = false
let customerContext = STPCustomerContext(keyProvider: MyAPIClient.sharedClient)
paymentMethodViewController = STPPaymentMethodsViewController(configuration: configuration,
theme: STPTheme.init(),
customerContext: customerContext,
delegate: self)
self.navigationController?.pushViewController(controller, animated: true)
Code For ApiClient to generate ephermal key
class MyAPIClient: NSObject, STPEphemeralKeyProvider {
static let sharedClient = MyAPIClient()
func createCustomerKey(withAPIVersion apiVersion: String, completion: #escaping STPJSONResponseCompletionBlock) {
let url = AppConstant.Server.EPHERMAL_KEY
let user = UserDefaultManager.shared.readUser()
let header: HTTPHeaders = ["api_token": user.apiToken ?? "",
"Content-Type": "application/json"]
Alamofire.request(url,
method: .get,
parameters: [
"api_version": apiVersion,
"id": user.id ?? -1
],
headers: header)
.validate(statusCode: 200..<300)
.responseJSON { responseJSON in
switch responseJSON.result {
case .success(let json):
completion(json as? [String: AnyObject], nil)
case .failure(let error):
completion(nil, error)
}
}
}
}
Then in delegate method
func paymentMethodsViewController(_ paymentMethodsViewController: STPPaymentMethodsViewController, didSelect paymentMethod: STPPaymentMethod) {
var paymentStripeId: String?
if let source = paymentMethod as? STPSource {
paymentStripeId = source.stripeID
} else if let card = paymentMethod as? STPCard {
self.stpCard = card
}
}
Try out this method. From stripe document.
let cardParams = STPCardParams()
cardParams.number = "4242424242424242"
cardParams.expMonth = 10
cardParams.expYear = 2021
cardParams.cvc = "123"
STPAPIClient.shared().createToken(withCard: cardParams) { (token: STPToken?, error: Error?) in
guard let token = token, error == nil else {
// Present error to user...
return
}
submitTokenToBackend(token, completion: { (error: Error?) in
if let error = error {
// Present error to user...
}
else {
// Continue with payment...
}
})
}

Invalid conversion from throwing function of type '(_, _, _) throws -> ()' to non-throwing function type '(URLResponse?, Data?, Error?) -> Void

I'm attempting to follow a tutorial from Ray Wenderlich's website to learn to use Instruments. The sample code is written is Swift 2 I believe so before I'm allowed to run it, I have to migrate the code to the latest Swift version. I've gotten half-way through the conversion errors but I'm stumped on the following area of code:
class Flickr {
let processingQueue = OperationQueue()
func searchFlickrForTerm(_ searchTerm: String, completion : #escaping (_ results: FlickrSearchResults?, _ error : NSError?) -> Void){
let searchURL = flickrSearchURLForSearchTerm(searchTerm)
let searchRequest = URLRequest(url: searchURL)
NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in
if error != nil {
completion(nil,error as! NSError)
return
}
var JSONError : NSError?
let resultsDictionary = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
if JSONError != nil {
completion(nil, JSONError)
return
}
switch (resultsDictionary!["stat"] as! String) {
case "ok":
print("Results processed OK")
case "fail":
let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:resultsDictionary!["message"]!])
completion(results: nil, error: APIError)
return
default:
let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"])
completion(nil, APIError)
return
}
let photosContainer = resultsDictionary!["photos"] as! NSDictionary
let photosReceived = photosContainer["photo"] as! [NSDictionary]
let flickrPhotos : [FlickrPhoto] = photosReceived.map {
photoDictionary in
let photoID = photoDictionary["id"] as? String ?? ""
let title = photoDictionary["title"] as? String ?? ""
let farm = photoDictionary["farm"] as? Int ?? 0
let server = photoDictionary["server"] as? String ?? ""
let secret = photoDictionary["secret"] as? String ?? ""
let flickrPhoto = FlickrPhoto(photoID: photoID, title: title, farm: farm, server: server, secret: secret)
return flickrPhoto
}
DispatchQueue.main.async(execute: {
completion(FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), nil)
})
}
}
fileprivate func flickrSearchURLForSearchTerm(_ searchTerm:String) -> URL {
let escapedTerm = searchTerm.addingPercentEscapes(using: String.Encoding.utf8)!
let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=30&format=json&nojsoncallback=1"
return URL(string: URLString)!
}
}
I get the error on the following line of code:
NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in
if error != nil {
completion(nil,error as! NSError)
return
}
I'm a little confused on how this should be amended using do, try, catch so any help would be appreciated just so I can get the app running to play around with Instruments.
Here is a link to the tutorial: https://www.raywenderlich.com/97886/instruments-tutorial-with-swift-getting-started
replace your Flickr class with this.
class Flickr {
let processingQueue = OperationQueue()
func searchFlickrForTerm(_ searchTerm: String, completion : #escaping (_ results: FlickrSearchResults?, _ error : NSError?) -> Void){
let searchURL = flickrSearchURLForSearchTerm(searchTerm)
let searchRequest = URLRequest(url: searchURL)
NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in
guard let data = data, error == nil else {
completion(nil, error as NSError?)
return
}
guard let jsonObject = try? JSONSerialization.jsonObject(with: data,
options: JSONSerialization.ReadingOptions(rawValue: 0)),
let resultsDictionary = jsonObject as? Dictionary<String, Any>
else
{
return
}
switch (resultsDictionary["stat"] as! String) {
case "ok":
print("Results processed OK")
case "fail":
let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:resultsDictionary["message"]!])
completion(nil, APIError)
return
default:
let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"])
completion(nil, APIError)
return
}
let photosContainer = resultsDictionary["photos"] as! NSDictionary
let photosReceived = photosContainer["photo"] as! [NSDictionary]
let flickrPhotos : [FlickrPhoto] = photosReceived.map {
photoDictionary in
let photoID = photoDictionary["id"] as? String ?? ""
let title = photoDictionary["title"] as? String ?? ""
let farm = photoDictionary["farm"] as? Int ?? 0
let server = photoDictionary["server"] as? String ?? ""
let secret = photoDictionary["secret"] as? String ?? ""
let flickrPhoto = FlickrPhoto(photoID: photoID, title: title, farm: farm, server: server, secret: secret)
return flickrPhoto
}
DispatchQueue.main.async(execute: {
completion(FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), nil)
})
}
}
fileprivate func flickrSearchURLForSearchTerm(_ searchTerm:String) -> URL {
let escapedTerm = searchTerm.addingPercentEscapes(using: String.Encoding.utf8)!
let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=30&format=json&nojsoncallback=1"
return URL(string: URLString)!
}
}
Sorry spacing is all messed up but the issue is you're not doing error handling correctly. When you do JSONSerialization it can throw so you have to wrap it in a do catch block or you can use ! to ignore the throw and crash if it throws an error or ? to return nil if it fails.

Alamofire POST dictionary with row data

Hi everyone I am currently using Swift 2.2 and Alamofire and I am doing a post/form request using a json. Here is the my current code:
func authenticateUserWithValues(passCode : String, userID : String, completion: (result: Bool, user : User?, message : String) -> Void) {
let urlString = NSString(format:"%#%#", kBaseURL, kCheckAuthenticationCodeURL) as String
let parameters: [String: String] = [ "code" : passCode,
"user_id": userID,
"application_type" : "2"]
Alamofire.request(.POST, urlString, parameters: parameters, encoding: .JSON)
.responseJSON { (response) in
switch response.result {
case .Failure(let error):
print(error)
if (error.code == -1009) {
completion(result: false, user: nil, message : kString_No_Internet_Connection)
}else{
completion(result: false, user: nil, message: kString_Unexpected_Error_Occured)
}
case .Success(let responseObject):
let response = responseObject as? [String:String]
var status : String = ""
var message : String = ""
if(response!["status"] != nil){
status = response!["status"]!
}
if(response!["message"] != nil){
message = response!["message"]!
}
if (status == "OK"){
let user : User = RealmManager().addUser(response!)
completion(result: true, user: user, message: message)
}else{
completion(result: false, user: nil, message: message)
}
print(responseObject)
}
}
}
Bu I need to change it to accept a raw body request of the same Dictionary.
Here is the post request in raw format using Swift 2.2:
func authenticateUserWithValues(passCode : String, userID : String, completion: (result: Bool, user : User?, message : String) -> Void) {
let urlString = NSString(format:"%#%#", kBaseURL, kCheckAuthenticationCodeURL) as String
let url:NSURL = NSURL(string: urlString)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "{\"code\" : \"\(passCode)\", \"user_id\" : \"\(userID)\", \"application_type\" : \"2\"}"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
if (error!.code == -1009) {
completion(result: false, user: nil, message : kString_No_Internet_Connection)
}else{
completion(result: false, user: nil, message: kString_Unexpected_Error_Occured)
}
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]
var status : String = ""
var message : String = ""
if(json["status"] != nil){
status = json["status"]! as! String
}
if(json["message"] != nil){
message = json["message"]! as! String
}
if (status == "OK"){
RealmManager().removerAllUsers()
RealmManager().addUser(json)
let user : User = RealmManager().getCurrentUser()!
completion(result: true, user: user, message: message)
}else{
completion(result: false, user: nil, message: message)
}
} catch let error as NSError {
completion(result: false, user: nil, message: error.localizedDescription)
}
}
task.resume()
}

Resources