Twitter OAuth on iOS - ios

I need to register on our server via twitter. I made registration with help of OAuth. When we make any request on our server we check our token is active, if our token is expired we make resign on our server and I need to resign in Twitter session, I do logout, but session is active. Android team do it with help
TwitterCore.getInstance().getSessionManager().clearActiveSession();
TwitterCore.getInstance().logOut();
. How can I do it on iOS? I use Swift Please, help me.
My code
func auth(userEmail: String?, successLoginCallback: ((usr : User) -> Void)?, failLoginCallback: ( (message: String) -> Void )?) {
Twitter.sharedInstance().sessionStore.reloadSessionStore()
Twitter.sharedInstance().startWithConsumerKey(twitterKey, consumerSecret: twitterSecret)
Twitter.sharedInstance().logInWithCompletion { (session, error) in
if session != nil {
TWTRAPIClient.clientWithCurrentUser().requestEmailForCurrentUser({ (twitterEmail, error) in
// oauth parameters
let oauthSession = TWTRSession(authToken: session!.authToken, authTokenSecret: session!.authTokenSecret, userName: session!.userName, userID: session!.userID)
let oauthSigning = TWTROAuthSigning(authConfig: Twitter.sharedInstance().authConfig, authSession: oauthSession)
let headers = oauthSigning.OAuthEchoHeadersToVerifyCredentials()
guard let authHeaders = headers as? [String : AnyObject] else {
return
}
var passEmail: String?
if userEmail != nil {
passEmail = userEmail
}
UserManager.sharedManager.logInViaTwitter(passEmail, parameters: authHeaders, success: { (user) in
self.userIsLogginedViaTwitter = true
self.twitterSuccessLogin(user)
print("user token", user.token?.expr)
successLoginCallback?(usr: user)
}, fail: { (errorMessage) in
if errorMessage != nil {
self.twitterFailsLogin(errorMessage!)
failLoginCallback?(message: errorMessage!)
}
})
})
}
if error != nil {
print(error?.localizedDescription)
}
}
}
func logOut(success: (() -> ())?) {
Twitter.sharedInstance().startWithConsumerKey(twitterKey, consumerSecret: twitterSecret)
guard let userID = Twitter.sharedInstance().sessionStore.session()?.userID else { return }
Twitter.sharedInstance().sessionStore.logOutUserID(userID)
userIsLogginedViaTwitter = false
let cookieStorage: NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
cookieStorage.cookies?.forEach({ (cook) in
cookieStorage.deleteCookie(cook)
})
success?()
}
// MARK: - Twitter functions
func logInViaTwitter(email: String?, parameters: [String : AnyObject], success: ((user: User) -> ())?, fail: ((errorMessage: String?) -> ())?) {
let url = "\(Networking.baseUrl)/auth/login/tw"
guard let oauth_url = parameters["X-Auth-Service-Provider"] as? String else { return }
guard let oauth_params = parameters["X-Verify-Credentials-Authorization"] as? String else { return }
var passParameters = [String : AnyObject]()
if email != nil {
passParameters = ["email" : email!, "oauth_url" : oauth_url, "oauth_params": oauth_params]
} else {
passParameters = ["oauth_url" : oauth_url, "oauth_params": oauth_params]
}
print("Twitter manager passParameters", passParameters, "Twitter manager passParameters")
Networking.manager.request(.POST, url, parameters: passParameters, encoding: .JSON, headers: nil).responseObject { (response: Response<RegisterResponse, NSError>) in
guard let result = response.result.value else {
fail?(errorMessage: nil)
return
}
if result.meta?.errors.count == 0 {
print(result.response)
guard let user = Mapper<User>().map(result.response) else {
fail?(errorMessage: nil)
return
}
// Save state in Twitter manager
TwitterManager.sharedManager.userIsLogginedViaTwitter = true
self.saveCurrentUser(user)
success?(user: user)
} else {
fail?(errorMessage: result.meta?.errors.first?.message)
}
}
}

We have changed the query logic, so that with every request we did not request information from the Twitter framework.

Related

How to post SwiftyJSON with Alamofire?

I would like to post a JSON via Alamofire.
but i'm not too sure how can i deal with it.
my swiftyJSON is in an array as my
how can i encode an array of JSON into a dictionaryObject? to suits
Alamofire's Parameters?
urlRequest = try JSONEncoding.default.encode(urlRequest, with: location)
my sample JSON looks like this:
"[{\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}]"
The trick is you'll need to convert it to Dictionary.
Sample snippet as follow:
```
// let assume swiftyJSON is a SwiftyJSON object (JSON)
if let data = swiftyJSON.rawString()!.data(using: .utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
Alamofire.request(url, method: .post, parameters: json, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
debugPrint(response)
}
} catch {
print("JSONSerialization error")
}
}
```
First add SwiftJSON to your project then
class func requestPOSTURL(serviceName:String,parameters: [String:Any]?, completionHandler: #escaping (JSON?, NSError?) -> ()) {
let headersSet: HTTPHeaders = [
"Authorization":GlobalAccesstoken,
"Accept": "application/json"
]
Alamofire.request(serviceName, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headersSet).responseJSON {
(response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
let json = JSON(data)
completionHandler(json,nil)
}
break
case .failure(_):
completionHandler(nil,response.result.error as NSError?)
break
}
}
}
AFWrapper.requestPOSTURL(serviceName: LapiUrl+"get_profile", parameters: params) { (response:JSON?, error:NSError?) in
if error != nil {
print(error!)
return
}
if response == nil {
return
}
print(response!)
var distRespoce = response!.dictionary?["response"]?.array?[0]
if (distRespoce?["status"].string == "true"){
let distuserData = distRespoce!.dictionary?["user_data"]
}
else{
print("no")
}
}
Try above code ..
You can do like this : -
Alamofire.request(urlString, method: .post, parameters: paramData, encoding:JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result)
{
case .success(_):
if response.result.value != nil
{
do
{
var dict : NSDictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(dict)
dict = UtilityClass.removeNullFromResponse(response: response.result.value! as! NSDictionary)
self.dataBlock(dict,nil)
}
catch
{
UtilityClass.hideHudLoading()
}
}
break
case .failure(_):
if response.result.error != nil
{
print(response.result.error!)
UtilityClass.hideHudLoading()
}
break
}
}
}
Simple Get post code, Easy to use, maintain and understand
Below is pod, you must need to use my code of json parsing.
#Network manager related
pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :tag => ‘4.0.1’
pod 'AlamofireNetworkActivityIndicator', '~> 2.0'
pod 'AlamofireObjectMapper', '~> 4.0.0'
pod 'SVProgressHUD', :git => 'https://github.com/SVProgressHUD/SVProgressHUD.git'
pod 'Reachability', '~> 3.2'
pod 'SwiftyJSON', '~> 3.0.0'
pod 'ObjectMapper', '~> 2.0'
pod 'SDWebImage', '~> 3.8'
Here, You can Call API in your view controller.
RegistrationService().login(email: (txtEmail.text)!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), password: self.txtPassword.text!, success: { (response) in
//Save data to user default
}) { (error) in
print(error as Any)
}
RegistrationService.swift //Service class, in which you can add api's
//
// RegistrationService.swift
// hotelBids
//
// Created by Mehul Parmar on 27/05/16.
// Copyright © 2017 Sooryen Innovation labs. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import ObjectMapper
import AlamofireObjectMapper
open class RegistrationService {
enum listOfApi : String {
case
login,
country
}
func country(_ success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
// create post request
NetworkManager().Get(listOfApi.country.rawValue,
paramaters: [:],
showLoader: true,
success: { responseObject in
success(responseObject)
}) { error in
failure(error)
}
}
func login(email: String, password: String, success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
// create request parameter
let requestParameters = ["email" : email,
"password" : password,
"user_role" : "customer"
]
// create post request
NetworkManager().POST(listOfApi.login.rawValue,
paramaters: requestParameters as [String : AnyObject]?,
showLoader: true,
success: { responseObject in
success(responseObject)
}) { error in
failure(error)
}
}
NetworkManager.swift
//
// NetworkManager.swift
// Constants.kAppName.localized()
//
// Created by Mehul Parmar on 08/06/16.
// Copyright © 2016 . All rights reserved.
//
import Foundation
import Alamofire
import SVProgressHUD
import SwiftyJSON
//import AMSmoothAlert
import ObjectMapper
import AlamofireObjectMapper
//used for facebook logour while invalid session
import FacebookLogin
//MARK : - Errors
enum NetworkConnection {
case available
case notAvailable
}
class NetworkManager {
let baseUrlDev_OLD : String = "https://hotelbids.com/" + "dev/" + "hb-app/" + "v3/" + "user/"
let baseUrlDev : String = "http://184.73.131.211/api/v1/"
//MARK : - Shared Manager
let sharedManager = SessionManager()
func getHeaders(_ urlString: String) -> [String: String] {
var headerDictionary = [String: String]()
if UserDetail.rememberToken != nil {
if (UserDetail.rememberToken?.length)! > 0 {
headerDictionary[Constants.KEY_remember_token] = "\(UserDetail.rememberToken!)"
}
}
/*
if let xapi = UserDefault.getXapi() {
headerDictionary[Constants.KEY_Xapi] = xapi
}
if let accessLanguage = UserDefault.getLanguage() {
headerDictionary[Constants.KEY_Language] = accessLanguage
}
if let userId = UserDefault.getUserId() {
headerDictionary[Constants.KEY_USER_ID] = userId
}
if let accessToken = UserDefault.getAccessToken() {
headerDictionary[Constants.KEY_AccessToken] = accessToken
}*/
print("urlString: \(urlString)\nheaderDictionary : \(headerDictionary)")
return headerDictionary
}
func printResponse(urlString: String, paramaters: [String: AnyObject]?, response: AnyObject) {
let dictResponce = self.getValidatedData(response as AnyObject)
// if dictResponce.boolValue {
if let paramatersTemp = paramaters {
if paramatersTemp.values.count > 0 {
let jsonParameters = JSON(paramatersTemp)
print("\n\n\nurlString : \(urlString) ,\n\n paramaters: \(jsonParameters) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
}
else {
print("\n\n\nurlString : \(urlString) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
}
}
else {
print("\n\n\nurlString : \(urlString) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
}
// } else {
// print("urlString : \(urlString) ,\n Response: \(String(describing: dictResponce))")
// }
}
func getValidatedData(_ response: AnyObject?) -> JSON {
//Removing null and <null>, and replacing number or integer to string
guard var dictResponse = response as? NSDictionary else{
return nil
}
dictResponse = (dictResponse.replacingNullsWithStrings() as NSDictionary).convertingNumbersToStrings()! as NSDictionary
let jsonResponce = JSON(dictResponse)
return jsonResponce
}
// MARK: - Get Method
func Get(_ urlString: String, paramaters: [String: AnyObject]? = nil, showLoader: Bool? = nil, success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
switch checkInternetConnection() {
case .available:
if let showLoader = showLoader {
if showLoader {
DispatchQueue.main.async {
// update some UI
UIApplication.shared.keyWindow?.showLoader()
}
}
}
Alamofire.request(baseUrlDev.add(urlString: urlString), method: .get, parameters: paramaters, encoding: URLEncoding.default, headers: self.getHeaders(urlString)).responseJSON (completionHandler: { response in
DispatchQueue.main.async {
if UIApplication.shared.isIgnoringInteractionEvents {
UIApplication.shared.endIgnoringInteractionEvents()
}
if let showLoader = showLoader {
if showLoader {
if SVProgressHUD.isVisible() {
SVProgressHUD.dismiss()
}
}
}
}
//Success
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
//Print response using below method
self.printResponse(urlString: urlString, paramaters: paramaters, response: (value as AnyObject))
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
}
else {
//Check response error using status code
if let strErrorReasonCode : Int = response.response?.statusCode {
if let data = response.data {
let jsonResponce = JSON(data: data)
if strErrorReasonCode == 500 {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
return
}
if let dictionary : NSDictionary = jsonResponce.dictionaryObject as NSDictionary? {
let responce : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictionary)
let authentication_Errors = 401
let authentication_Errors_Range = 400..<500
let Alamofire_Error = -1005
if authentication_Errors == strErrorReasonCode {
print("\n\n\n\nauthentication_Errors :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
self.isUnAuthotized()
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(strErrorReasonCode) {
print("\n\n\n\nauthentication_Errors_Range :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
CustomAlert().ShowAlert(responce.message)
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(Alamofire_Error) {
self.POST(urlString, paramaters: paramaters, showLoader: showLoader, success: { (responseObject) in
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
}
}, failure: {_ in
failure(jsonResponce)
})
}
}
else {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
}
}
}
else {
failure(nil)
}
}
})
case .notAvailable:
if let _ = showLoader {
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kNoInternet, duration: 3.0, position: "bottom" as AnyObject)
}
failure(JSON(AppAlertMsg.kNoInternet))
print("No internet")
}
}
// MARK: - POST Method
func POST(_ urlString: String, paramaters: [String: AnyObject]? = nil, showLoader: Bool? = nil, success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
switch checkInternetConnection() {
case .available:
if let showLoader = showLoader {
if showLoader {
DispatchQueue.main.async(execute: {
if !UIApplication.shared.isIgnoringInteractionEvents {
UIApplication.shared.beginIgnoringInteractionEvents()
}
SVProgressHUD.show(withStatus: AppAlertMsg.kPleaseWait)
})
}
}
sharedManager.request(baseUrlDev.add(urlString: urlString), method: .post, parameters: paramaters, encoding: JSONEncoding.default, headers: self.getHeaders(urlString)).validate().responseJSON(completionHandler: { response in
DispatchQueue.main.async {
if UIApplication.shared.isIgnoringInteractionEvents {
UIApplication.shared.endIgnoringInteractionEvents()
}
if let showLoader = showLoader {
if showLoader {
if SVProgressHUD.isVisible() {
SVProgressHUD.dismiss()
}
}
}
}
//Success
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
//Print response using below method
self.printResponse(urlString: urlString, paramaters: paramaters, response: (value as AnyObject))
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
} else {
//Check response error using status code
if let strErrorReasonCode : Int = response.response?.statusCode {
if let data = response.data {
let jsonResponce = JSON(data: data)
if strErrorReasonCode == 500 {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
return
}
if let dictionary : NSDictionary = jsonResponce.dictionaryObject as NSDictionary? {
let responce : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictionary)
let authentication_Errors = 401
let authentication_Errors_Range = 400..<500
let Alamofire_Error = -1005
if authentication_Errors == strErrorReasonCode {
print("\n\n\n\nauthentication_Errors (jsonResponce)\n\n\n\n")
self.isUnAuthotized()
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(strErrorReasonCode) {
print("\n\n\n\nauthentication_Errors_Range :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
CustomAlert().ShowAlert(responce.message)
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(Alamofire_Error) {
self.POST(urlString, paramaters: paramaters, showLoader: showLoader, success: { (responseObject) in
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
}
}, failure: {_ in
failure(jsonResponce)
})
}
}
else {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
}
}
}
else {
failure(nil)
}
}
})
case .notAvailable:
if let _ = showLoader {
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kNoInternet, duration: 3.0, position: "bottom" as AnyObject)
}
failure(JSON(AppAlertMsg.kNoInternet))
print("No internet")
}
}
// MARK: - No Internet Connection
func checkInternetConnection() -> NetworkConnection {
if isNetworkAvailable() {
return .available
}
return .notAvailable
}
// MARK: - Check Status
func isValidated(_ response: AnyObject?) -> (Bool, JSON) {
//Removing null and <null>, and replacing number or integer to string
guard var dictResponse = response as? NSDictionary else{
return (false,nil)
}
dictResponse = (dictResponse.replacingNullsWithStrings() as NSDictionary).convertingNumbersToStrings()! as NSDictionary
let jsonResponce = JSON(dictResponse)
let responseModel : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictResponse)
/* //
HTTP Status Code
200 – Success/OK
4xx – Authentication Errors
5xx – Service Errors
*/ //
guard let statusCodeInt = responseModel.code.toInt() else {
print("code is not proper")
return (false,jsonResponce)
}
let success_Range = 200..<300
let authentication_Errors = 401
let authentication_Errors_Range = 400..<500
let service_Errors_Range = 500..<600
if success_Range.contains(statusCodeInt) {
// all okey
return (true, jsonResponce)
}
else if authentication_Errors == statusCodeInt {
print("service_Errors_Range :\(statusCodeInt)")
self.isUnAuthotized()
return (false,jsonResponce)
}
else if authentication_Errors_Range.contains(statusCodeInt) {
print("authentication_Errors_Range :\(statusCodeInt)")
CustomAlert().ShowAlert(responseModel.message)
return (false,jsonResponce)
}
else if service_Errors_Range.contains(statusCodeInt) {
print("service_Errors_Range :\(statusCodeInt)")
CustomAlert().ShowAlert(responseModel.message)
return (false,jsonResponce)
}
else {
return (false,nil)
}
}
func isUnAuthotized() {
// we have to logout, bcos session expired , or user unauthorized
CustomAlert().ShowAlert(isCancelButton: false, strMessage: AppAlertMsg.kUnAuthotized) { (isYESClicked) in
if isYESClicked {
//Delete all data from user default
//Set sign in as Home screen
print("set to Login view controller ")
GmailClass.sharedInstance().signOut()
LoginManager().logOut()
UserStatus = UserType.Fresh.rawValue
let deviceTokenTemp = DeviceToken
if let bundle = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundle)
}
DeviceToken = deviceTokenTemp
Constants.appDelegate.logoutSuccess()
}
}
}
// MARK: - Loader method
class func ShowActivityIndicatorInStatusBar() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
class func HideActivityIndicatorInStatusBar() {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
extension String {
func add(urlString: String) -> URL {
return URL(string: self + urlString)!
}
func EncodingText() -> Data {
return self.data(using: String.Encoding.utf8, allowLossyConversion: false)!
}
}

Twitter SLRequest Authentication Error

I have been trying to retrieve twitter user data utilizing the built in iOS Accounts and Twitter frameworks.
I am getting access to the user account on the phone successfully. However, when making the SLRequest to twitter I receive an non authenticated error. I was under the impression that assigning the user ACCount to the twitter SLRequest.account fulfilled the OAuth parts necessary.
Code is from test project I have set up
Any feedback is greatly appreciated!
var accountsArray = AnyObject
var account = ACAccount()
override func viewDidLoad() {
super.viewDidLoad()
let accountStore: ACAccountStore = ACAccountStore()
let twitterAccountType: ACAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
let url = NSURL(string: "https://api.twitter.com/1.1/users/show.json")
let params: NSDictionary = ["field": "user_id, screen_name"]
accountStore.requestAccessToAccountsWithType(twitterAccountType, options: nil, completion: { (success, error) -> Void in
if success {
let account = accountStore.accountsWithAccountType(twitterAccountType)
if let userAccount = account.first as? ACAccount {
self.accountsArray.append(userAccount)
let twitterRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: url, parameters: params as [NSObject : AnyObject])
From what i have found i thought the line below covered the OAuth requirement for twitter api version 1.1
twitterRequest.account = userAccount
twitterRequest.performRequestWithHandler({ (responseData : NSData?, urlResponse : NSHTTPURLResponse?, error : NSError?) -> Void in
print("data : \(responseData)")
if let response = responseData {
var dict = NSDictionary()
do {
dict = try! NSJSONSerialization.JSONObjectWithData(response, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
}
print(dict)
} else if error != nil {
print("Error : \(error)")
}
})
}
} else if (error != nil) {
print("nooope")
}
})
}
}
Whats returned from the dictionary:
{
errors = (
{
code = 50;
message = "User not found.";
}
);
}
params dictionary should be:
["screen_name": "username"]

Return Bool in Alamofire closure

I use Swift 2 and Xcode 7.1.
I have a function who connect my users, but it will connect at my database with HTTP. I use Alamofire for execute this request. I want to know, from a view controller if the user is connected.
I have my function connect in a class. And i test connection in a ViewController.
Like this :
class user {
// ...
func connectUser(username: String, password: String){
let urlHost = "http://localhost:8888/project350705/web/app_dev.php/API/connect/"
let parametersSymfonyG = [
username, password
]
let url = UrlConstruct(urlHost: urlHost).setSymfonyParam(parametersSymfonyG).getUrl()
//var userArray = [String:AnyObject]()
Alamofire.request(.GET, url)
.responseString { response in
if let JSON = response.result.value {
var result = self.convertStringToDictionary(JSON)!
if result["status"] as! String == "success"{
let userArray = result["user"] as! [String:AnyObject]
userConnect = self.saveUser(userArray)
} else{
print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
}
return ""
}
}
}
// ...
}
class MyViewController: UIViewController {
// ...
#IBAction func connect(sender: AnyObject?) {
// CONNECTION
User.connectUser(self.username.text!, password: self.password.text!)
// CHECK
if userConnect != nil {
print("connected")
}else{
print("NotConnected")
}
}
// ...
}
First solution : Return
To do so would require that my function returns a Boolean.
Only I can not use return.
Alamofire.request(.GET, url)
.responseString { response in
if let JSON = response.result.value {
var result = self.convertStringToDictionary(JSON)!
if result["status"] as! String == "success"{
let userArray = result["user"] as! [String:AnyObject]
userConnect = self.saveUser(userArray)
} else{
print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
}
return "" // Unexpected non-void return value in void function
}
}
Second solution :
I can also test if the user has been logged, but before testing, I must wait for the function have finished loading.
users.connectUser(self.username.text!, password: self.password.text!)
// after
if userConnect != nil {
print("connected")
}else{
print("NotConnected")
}
I would prefer return a boolean. It will facilitate the processing.
Do you have a solution ?
I would suggest employing a completion handler in your connectUser method:
func connectUser(username: String, password: String, completion: #escaping (Bool) -> Void) {
// build the URL
// now perform request
Alamofire.request(url)
.responseString { response in
if let json = response.result.value, let result = self.convertStringToDictionary(json) {
completion(result["status"] as? String == "success")
} else {
completion(false)
}
}
}
You can then call it using:
users.connectUser(username.text!, password: password.text!) { success in
if success {
print("successful")
} else {
print("not successful")
}
}
// But don't use `success` here yet, because the above runs asynchronously
BTW, if your server is really generating JSON, you might use responseJSON rather than responseString, further streamlining the code and eliminating the need for convertStringToDictionary:
func connectUser(username: String, password: String, completion: #escaping (Bool) -> Void) {
// build the URL
// now perform request
Alamofire.request(url)
.responseJSON { response in
if let dictionary = response.result.value as? [String: Any], let status = dictionary["status"] as? String {
completion(status == "success")
} else {
completion(false)
}
}
}
If you've written your own server code to authenticate the user, just make sure you set the right header (because responseJSON not only does the JSON parsing for you, but as part of its validation process, it makes sure that the header specifies JSON body; it's good practice to set the header, regardless). For example in PHP, before you echo the JSON, set the header like so:
header("Content-Type: application/json");
The completion handler of your Alamofire.request method is asynchronous and it doesn't have a return type specified in its signature. Thats why you see an error when you provide a return statement in your completion handler closure.
You will have to split your request and response processing to separate methods and call the response processing method instead of using return statement.
Alamofire.request(.GET, url).responseString { response in
if let JSON = response.result.value {
var result = self.convertStringToDictionary(JSON)!
if result["status"] as! String == "success"{
let userArray = result["user"] as! [String:AnyObject]
userConnect = self.saveUser(userArray)
processSuccessResponse() //Pass any parameter if needed
} else{
print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
processFailureResponse() //Pass any parameter if needed
}
}
}
func processSuccessResponse() {
//Process code for success
}
func processFailureResponse() {
//Process code for failure
}
My preferred way of doing this is to call a function in the completion handler. You can also set a boolean flag in order to check if the user is connected at any given time.
func connectUser(username: String, password: String, ref: MyClass) {
Alamofire.request(.GET, url)
.responseString { response in
var userIsConnected = false
if let JSON = response.result.value {
var result = self.convertStringToDictionary(JSON)!
if result["status"] as! String == "success"{
let userArray = result["user"] as! [String:AnyObject]
userConnect = self.saveUser(userArray)
userIsConnected = true
} else {
print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
}
} else {
print("Response result nil")
}
ref.finishedConnecting(userIsConnected)
}
}
}
class MyClass {
var userIsConnected = false
func startConnecting() {
connectUser(username, password: password, ref: self)
}
func finishedConnecting(success: Bool) {
userIsConnected = success
... post-connection code here
}
}

can not get twitter user details in swift

I am trying to load twitter user details using this code
#IBAction func twitterLogin(sender: UIButton) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
let accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: { (granted : Bool, error : NSError?) -> Void in
if error != nil {
print("Error in getting permission : \(error)")
} else {
if granted {
let accounts : NSArray = self.accountStore.accountsWithAccountType(accountType)
if accounts.count > 0 {
self.twitterAccount = accounts.lastObject as? ACAccount
let url = NSURL(string: "https://api.twitter.com/1.1/users/show.json")
let parameters : NSDictionary = ["fields": "user_id,screen_name"]
let twitterRequest : SLRequest = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: SLRequestMethod.GET, URL: url, parameters: parameters as [NSObject : AnyObject])
twitterRequest.account = self.facebookAccount
twitterRequest.performRequestWithHandler({ (responseData : NSData?, urlResponse : NSHTTPURLResponse?, error : NSError?) -> Void in
if error != nil {
print("Error : \(error)")
} else {
// print("data : \(responseData)")
if let response = responseData {
var dict = NSDictionary()
do {
dict = try! NSJSONSerialization.JSONObjectWithData(response, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
} catch let error as NSError {
print("Error : \(error)")
}
print(dict)
}
}
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.showAlert(nil, message: "Permission not granted")
})
}
}
})
} else {
self.askForSettingsChange("No Twitter Account", message: "There are no Twitter accounts configured. You can add or create Twitter account in Settings")
}
}
output
{
errors = (
{
code = 215;
message = "Bad Authentication data.";
}
);
}
Get many examples but cannot get proper solution.
I think that may be problem in api call or may be parameters.
Try to correct but no success
Fabric is sdk which is providing twitter login with easy authentication via either guest or user login.
Twitter login using Fabric
Sample Code written in Swift https://docs.fabric.io/ios/twitter/index.html
If you want to use raw REST calls against the API, follow the OAuth details in developer documentation
https://dev.twitter.com/oauth

Instagram Parse Authentication to generate Session Token Swift IOS

How do i create the session token required to authenticate a user in parse.
I have been able to follow this blog post http://blog.parse.com/announcements/bring-your-own-login/ but i don't know how to generate a session token using Swift(IOS).
This is what i have so far.
func doAuthInstagram() {
let oauthswift = OAuth2Swift(
consumerKey: Instagram["consumerKey"]!,
consumerSecret: Instagram["consumerSecret"]!,
authorizeUrl: "https://api.instagram.com/oauth/authorize",
responseType: "token"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorize_url_handler = WebViewController()
oauthswift.authorizeWithCallbackURL(NSURL(string: "oauth-swift://oauth-callback/instagram")!, scope: "likes+comments", state: state,
success: { (credential, response, parameters) -> Void in
let url: String = "https://api.instagram.com/v1/users/self/?access_token=\(credential.oauth_token)"
let parameters: Dictionary = Dictionary<String, AnyObject>()
oauthswift.client.get(url, parameters: parameters,
success: { (data, response) -> Void in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
let user = PFUser()
if let userData: AnyObject = jsonDict["data"] {
let name: String = userData["full_name"] as! String
let username: String = userData["username"] as! String
let id: String = userData["id"] as! String
let profileImage: String = userData["profile_picture"] as! String
user.username = username
user.password = id
user["name"] = name
user["profileImage"] = profileImage
user.signUpInBackgroundWithBlock { (success, error) -> Void in
if (success) {
println("user: \(user)")
PFUser.logInWithUsernameInBackground(username, password: id, block: { (user, error) -> Void in
if user != nil {
self.performSegueWithIdentifier("loginSegue", sender: self)
} else {
ProgressHUD.showError("\(error)")
}
})
} else if let error = error!.userInfo!["error"] as? NSString {
if error == "username \(username) already taken" {
PFUser.logInWithUsernameInBackground(username, password: id, block: { (user, error) -> Void in
if user != nil {
self.performSegueWithIdentifier("loginSegue", sender: self)
} else {
ProgressHUD.showError("\(error)")
}
})
} else {
ProgressHUD.showError("\(error)")
}
}
}
}
}, failure: { (error) -> Void in
ProgressHUD.showError("\(error)")
})
}) { (error) -> Void in
println(error.localizedDescription)
ProgressHUD.showError("\(error.localizedDescription)")
}
}

Resources