log in yii2 account using Alamofire - ios

I'm trying to log in into account using api and POST request in Swift 3 with Alamofire library. Here is my code:
#IBAction func logInButtonClick(_ sender: Any) {
Alamofire.request(".../api/login", method: .post, parameters: ["email": "mail1#gmail.com", "password" : "qwerty"], encoding: JSONEncoding.default).responseString { (response) in
if let result = response.result.value {
print(result)
}
}
}
When I'm trying to get an access_token field (user exists and api works correctly, for sure) from this request, I am not getting it.
The fact is my api user's url is always the same (I've already read this: How to pass access token to Alamofire?) and looks like ".../api/login/" and it doesn't depend on user e-mail or username, and I don't know how I should deal with it in a such way. Thanks in advance.

Related

Alamofire POST request with nested parameters returns nothing

Hello I am trying to use Alamofire for my HTTP requests. It is working with parameters that are not included any nested parameter. Normally, my url is working with following on the Google Chrome.
http://111.222.33.4:12345/my_server/dispatch?cmd=ext_getReferanceData&jp=%7b%22rfName%22:%22RF_ABC%22%7d&token=123
and the decoded version of above url is
http://111.222.33.4:12345/my_server/dispatch?cmd=ext_getReferanceData&jp={"rfName":"RF_ABC"}&token=123
It works fine when I paste it into any browser. However when I try to send following post request with Alamofire
let parameters3: [String: Any] = [
"cmd": "ext_getReferanceData",
"jp": [
"rfName": "RF_ABC"
],
"token": "123"
]
Alamofire.request("http://111.222.33.4:12345/my_server/dispatch", method: .get, parameters: parameters3, encoding: JSONEncoding.default).responseJSON { (response) in
}
It is returning
FAILURE:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
What could be the reason of it am I sending parameters wrong or is there anything that I am missing?
Edit: I also checked other questions about the error but the problem is about parameters that I am trying to send because there is " and { in the parameters but I could not send in the request.
have you considered printing the response being sent and confirming it that it's indeed the stuff you're trying to send?
You can do a couple of things to improve
Make the method .post
Try to use .validate() for added reliability
The way I do it is something like:
let submissionURL = URL(string: "https://blablabla.com/script.php")
sendAlamofireRequest(submissionURL: submissionURL!, parameters: parameters, chosenTrackerStr: chosenTrackerString) //function call
//function declaration
func sendAlamofireRequest(submissionURL: URL, parameters: Parameters, chosenTrackerStr: String){
Alamofire.request(submissionURL, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseString() { (response) in
//actual code goes here
}
}
Maybe try to play around with the alamofire request and check its documentation to see the suggested approach :)

Alamofire request to twilio swift

I'm trying to get an SMS from twilio.com but get nil in response. Can anyone say what I'm doing wrong?
class SMSVerificationService: NSObject {
static let sharedInstance = SMSVerificationService()
func SMSRequest(countryCode:String, phoneNumber: String) {
let accountSid = "ACc4d9785419f144412823ff20as34660c3d"
let authToken = "4wqecx41f8999caa23735da214" // changed :)
let url = URL(string: "https://\(accountSid):\(authToken)#api.twilio.com/2010-04-01/Accounts\(accountSid)/Messages")
print("url", url!)
let parameters = [
"To": "+37378847884",
"From" : "+14243960339",
"Body": "Hi daddy"
]
Alamofire.request(url!, method: .post, parameters: parameters,
encoding: JSONEncoding.default, headers: [:]).responseJSON { response in
let response = String(describing: response.result.value)
print(response)
}
}
}
Twilio developer evangelist here.
We do not recommend that you make requests to the Twilio API directly from your native application. To do so, you would need to store or retrieve your account SID and auth token in the application somewhere. If you do this, then a malicious attacker could get access to your credentials and abuse your Twilio account.
This is actually known as the Eavesdropper vulnerability and was written about earlier this year.
Instead we recommend that you create a web application and send the API requests from there. There is a blog post on how to do that here: https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
I notice that your class is called SMSVerificationService too. If you are looking to build phone verification, then I recommend you take a look at the Twilio Verify API that does a lot of the work for you.

Retrieveing media liked by the user returns nothing

I'm trying to get the media liked by the logged in user. I do the authentication process and get an access token like this.
1312564049.dd97f3a.e9gw8d5516414d348c0b34f328e80fb1
I made sure to ask for public_content scope permission as well.
Then I call the /users/self/media/liked endpoint passing this token.
let urlString = "https://api.instagram.com/v1/users/self/media/liked"
let params = ["access_token": token]
Alamofire.request(.GET, urlString, parameters: params, encoding: .URL, headers: nil).responseJSON { response in
print(response.description)
}
But I get the following as the result.
{
data = (
);
meta = {
code = 200;
};
pagination = {
};
}
There are many photos liked by the user account I use. So I'm baffled why this returns empty. Is this because I'm in sandbox mode? Or something wrong with this endpoint? Because I checked /users/self and /users/self/media/recent and they both returned results.
Its because of the sanbox mode.
https://www.instagram.com/developer/sandbox/
Data is restricted to the 10 users and the 20 most recent media from each of those users

Authenticated http request swift Alamofire

I'm struggling with getting this to work to make request to my API. Without a token works, but when I try to add additional headers, things turn to be complicated, for me.
First, the structure.
one class called: APIAsyncTask that makes the requests
one class called APIParams, just a data holder to send parameters to the APIAsyncTask class.
one class called DatabaseAPI that makes that builds the parameters, and send that to the APIAsyncTask class.
DatabaseAPI
func someMethod()
{
let task = APIAsyncTasks()
task.registerCallback { (error, result) -> Void in
print("Finished task, back at DatabaseAPI")
}
let params2 = APIParams(request: .GET, apiPath: "Posts/1", apiToken: "4iTX-56w")
task.APIrequest(params2)
}
APIAsyncTask
This part is for fixing another error, because manager was not global, the task got cancelled quickly.
var manager : Manager!
init(authenticatedRequest : Bool, token: String?)
{
manager = Alamofire.Manager()
print("Pre \(manager.session.configuration.HTTPAdditionalHeaders?.count)")
if(authenticatedRequest && token != nil)
{
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders!
defaultHeaders["Authorization"] = "bearer \(token)"
let configuration = Manager.sharedInstance.session.configuration
configuration.HTTPAdditionalHeaders = defaultHeaders
manager = Alamofire.Manager(configuration: configuration)
}
print("Post \(manager.session.configuration.HTTPAdditionalHeaders?.count)")
}
After some decision making, it comes down to this part.
private func GetRequest(url: String!,token : String?, completionHandler: (JSON?, NSURLRequest?, NSHTTPURLResponse?, NSError?) -> () ) -> ()
{
print("Begin Get Request")
if(token != nil)//if token is not nil, make authenticated request
{
print("just before request: \(manager.session.configuration.HTTPAdditionalHeaders?.count)")
manager.request(.GET, url, parameters: nil, encoding: .JSON).responseJSON { (request, response, json, error) in
print("Get Request (authenticated), inside alamofire request")
var resultJson : JSON?
if(json != nil)
{
resultJson = JSON(json!)
}
completionHandler(resultJson, request, response, error)
}
}
else
{
//working part without token
So as the code is now, I get an error on completing:
Mattt himself gives the answer of using Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders
, so that should be fine...
I suspect it has something to do with the multiple threads, according to this blog. Or, since it is something about CFNetwork, it could be because my API does not use SSL? I disabled NSAppTransportSecurity
I'm kind of new to swift, so examples would be really appreciated! Thankyou!
So the majority of your code looks solid.
The error leads me to believe that CFNetwork is having difficulty figuring out how to compute the protection space for the challenge. I would also assume you are getting a basic auth challenge since you are attaching an Authorization header.
Digging through your logic a bit more with this in mind led me to see that your not attaching your token to the string properly inside the Authorization header. You need to do the following instead.
defaultHeaders["Authorization"] = "bearer \(token!)"
Otherwise your Authorization header value is going to include Optional(value) instead of just value.
That's the only issue I can see at the moment. If you could give that a try and comment back that would be great. I'll update my answer accordingly if that doesn't actually solve your problem.
Best of luck!
You can add your headers in your request with Alamofire 2 and Swift 2.
For an example: go to example

sending accessToken to server using swift ios

I am trying to use facebook ios login sdk. I get the access Token using below code. Now i want to send this token to a server so that server can validate this token by making a call to facebook server.
I am using the below code to get the accessToken , i am using swift in ios 8.
var accessToken = FBSession.activeSession().accessTokenData
When i am trying to send this token to server getting an error saying that type of accessToken is not convertible to NSString.
Please help me where i am wrong.
First, make sure that you have an open session. I use this approach in my AppDelegate:
FBSession.openActiveSessionWithAllowLoginUI(false)
Second, you can get accessToken as a string from accessTokenData:
var myToken = FBSession.activeSession().accessTokenData.accessToken
From there, you can send it to your server however you want. I tried a couple request wrappers until I settled on Net. Getting your token to your server is pretty easy if you have a library like Net so that you don't have to handle the low level network request interfaces:
func doLogin() -> Void {
let net = Net(baseUrlString: "http://myhost.com/")
let url = "auth/facebook_access_token"
let params = ["access_token": myToken]
net.GET(url, params: params, successHandler: { responseData in
let result = responseData.json(error: nil)
// Do something with whatever you got back
NSLog("result \(result)")
}, failureHandler: { error in
NSLog("Error")
})
}
Good luck! I hope I was able to help!

Resources