iOS facebook login without SDK http post Swift/Obj-C - ios

Let me start off by saying the purpose of this code is so I can practice on various other sites with login pages or forms. This is why I do no wish to use Facebook's SDK. So please...
Do not point me to Facebook's SDK (many other questions specifically asking for without SDK have been given SDK answers)
Ideally I would like to create an app that has preset information that will login to a site (such as Facebook) when the app opens or a button is pressed
I'd prefer an answer in Swift but I can read Objective - C and may be able to decipher it
Here is some sample code I've tried:
let myURL = NSURL(string: "https://mobile.facebook.com")
let request = NSMutableURLRequest(URL: myURL!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-type")
let postString = "email=*email&pass=*pass&login=Log In"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let postInt = postString.characters.count
request.setValue("\(postInt)", forHTTPHeaderField: "Content-length")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
}
if let HTTPResponse = response as? NSHTTPURLResponse {
let sCode = HTTPResponse.statusCode
if sCode == 200 {
// Then do something.
self.webView.loadRequest(request)
}
}
print("respone = \(response)")
}
task.resume()
*email = The user's email
*pass = The user's password
note: email, pass, Log In were taken from the form name values on the html code.
Current results- I am able to get the email to appear on opening of the app but the password is blank and it doesn't appear to have attempted a log in.
Please help and let me know if you need any clarifications
PS I've been looking for about a week now to no avail so I apologize if the answer is somewhere. I am not completely familiar with terminology to look for it.

Related

CreateUploadSession for OneDrive upload using Microsoft Graph API: The request is malformed or incorrect

Using MSAL 1.1.24 & making API calls in an iOS app that supports uploading to OneDrive for a year now.
Some users reported that they sometimes (not 100% of the time) see their upload fail.
The error message is "The request is malformed or incorrect".
Attached is a screenshot with the full error message returned by the servers:
Whats is wrong in the URL?
This is how I create the request:
/* REQUEST */
guard let validPathForURL = uploadPath.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
let url = URL(string: "\(ODManager.kGraphEndpoint)"+validPathForURL+":/createUploadSession") else {
DLog("Invalid URL")
completion(QSTransferResult.failure(QSTransferError.ResourceNotFound), nil)
return
}
var request = ODManager.shared.createURLRequestWithToken(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// Conflict management
let fileExistBehavior = fileExistProcedure == .keepBoth ? "rename" : "replace"
let params = ["item": [
"#microsoft.graph.conflictBehavior":fileExistBehavior,
"name":fileName],
"fileSize":fileSize,
] as [String : Any] // name must be the same as the one mentioned in the URL (in other words, the file name must be in both place)
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
The server returning the issue:
I'm going to take a stab at this... I think when it's failing the #name.conflictBehavior annotation is NOT the first property in the JSON document provided to the service (it doesn't actually have to be first - it can be after another instance annotations, but NOT properties). Now the fact that it doesn't happen often is a little odd... is it possible the annotation is only added on occasion (e.g. when a conflict is detected you pop up UI to ask if the user wants to overwrite)?

login user with GET request swift

I have created a screen with a text field called customer_number text field and another screen with a text field called password text field. I want to integrate my app with an existing API made by the backend developers. I am new to IOS Development and I don't know how to go about it. How do I make a get request and pass the login credentials for the user to login?
I want to get the customer number from the API and pass it to the app and enable the customer to log in.
I think this question is too big and complex to be replied exhaustively. You didn't tell us about the API. What kind of input does it take? What kind of response?
Supposing the simplest case. You API expects JSON objects as input and respond with another JSON object containing the information you request.
I usually do tasks like this using the NSURLRequest.
let js = ["Username":username, "Password":password]
let session = URLSession.init(configuration: .default)
let url = URL(...)
var req = URLRequest.init(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
req.httpMethod = "POST"
// Add some header key-value pairs
req.addValue(..., forHTTPHeaderField: ...)
...
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else { return }
guard let responseData = data else { return }
let code = (response as! HTTPURLResponse).statusCode
// Checking for code == 200 states for authorised user. Generally log-in APIs should return some 4xx code if not allowed or non-authorised user.
if code == 200 {
// Now we try to convert returned data as a JSON object
do {
let json = try JSONSerialization.jsonObject(with: responseData, options: [])
// use your json object here, for example checking if contains the user number...
} catch {
// handle errors
}
}
}
task.resume()
I coded this very quickly, please check the correctness of al mechanism!

What is the best way to add data and upload files to Rest api

My iOS application allows a user to submit a complaint to an online REST API with the following parameters:
Data Fields: such as name, phone number, ...
Voice: recorded from microphone
Image/Video: selected from photo gallery
1- how can i do that with swift?
2- how to get back an ID field from the server after submission?
3- how to manage an upload progress for the voice and media files?
Regards
After few weeks working hardly on it, here is my experience using Swift 3.1 which is run smoothly:
//use POSTMAN plugin in Chrome browser to get the read header for your API (optional):
let headers = [
"cache-control": "no-cache",
"postman-token": "00000000-1111-2222-3333-444444444"]
//this is the important part:
let strQuery: String = "mobileNo=" + txtMobileNB.text! + "&fullname=" + txtName.text!
let request = try? NSMutableURLRequest(url: NSURL(string: "http://service.website.com/apiname/?" + strQuery)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request?.httpMethod = "POST"
request?.allHTTPHeaderFields = headers
if request != nil {
let session = URLSession.shared
let dataTask = session.dataTask(with: request! as URLRequest) {data,response,error in
if let content = data
{
let responseData = String(data: content, encoding: String.Encoding.utf8)
//feedback from server:
print(responseData)
//call success function:
self.showDone()
} else {
//call error function:
self.showWrong()
}
}
dataTask.resume()
} else {
//call error function:
self.showWrong()
}
Regarding the other part "how to upload", i've found this framework is a good one (called rebekka) to start your upload project through iOS apps.
hope this helps someone :)

How to get a MS Translator access token from Swift 3?

I am trying to work with a MS Translator API from Swift 3 (right now playing in playgrounds, but the target platform is iOS). However, I got stuck when I was trying to get an access token for OAuth2. I have following code (I tried to port the code from example at Obtaining an access token):
let clientId = "id".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let clientSecret = "secret".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let scope = "http://api.microsofttranslator.com".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let translatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
let requestDetails = "grant_type=client_credentials&client_id=\(clientId)&client_secret=\(clientSecret)&scope=\(scope)"
let postData = requestDetails.data(using: .ascii)!
let postLength = postData.count
var request = URLRequest(url: URL(string: translatorAccessURI)!)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("\(postLength)", forHTTPHeaderField: "Content-Length")
request.httpBody = postData
URLSession.shared.dataTask(with: webRequest) { (returnedData, response, error) in
let data = String(data: returnedData!, encoding: .ascii)
print(data)
print("**************")
print(response)
print("**************")
print(error)
}.resume()
Of course, I used a valid clientId and a valid clientSecret.
Now the callback prints following information. First, the returnedData contain a message that the request was invalid, along with a following message:
"ACS90004: The request is not properly formatted."
Second, the response comes with a 400 code (which fits the fact that the request is not properly formatted).
Third, the error is nil.
Now I was testing the call using Postman, and when I used the same URI, and put the requestDetails string as a raw body message (I added the Content-Type header manually), I got the same response. However, when I changed the body type in Postman UI to application/x-www-form-urlencoded and typed in the request details as key value pairs through its UI, the call succeeded. Now it seems that I am doing something wrong with the message formatting, or maybe even something bad with the Swift URLRequest/URLSession API, however, I cannot get a hold on to what. Can somebody help me out, please? Thanks.
OK, so after some more desperate googling and experimenting I have found my error. For the future generations:
The problem resided in encoding the parameters in the body of the PUT http request. Instead of:
let scope = "http://api.microsofttranslator.com"
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
I have to use the following:
let scope = "http://api.microsofttranslator.com"
.addingPercentEncoding(withAllowedCharacters:
CharacterSet(charactersIn: ";/?:#&=$+{}<>,").inverted)!
Seems that the API (or the HTTP protocol, I am not an expert in this) have problems with / and : characters in the request body. I have to give credit to Studiosus' answer on Polyglot issue report.

Receiving projects list using JIRA API

I want make simple JIRA assistant for iOS but cannot figure out why API call return empty array.
For example, using this code i'm trying to get projects list:
let request = NSMutableURLRequest(URL: "http://myjira.atlassian.net/rest/api/2/project".URL!)
request.addValue("Basic " + emailAndPasswordAsb64String, forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
guard let data = data, responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String where !responseString.isEmpty else {
print("No valid response!", appendNewline: true)
return
}
print("Response: " + responseString, appendNewline: true)
}.resume()
But getting this: Response: []
I'm also tried to use some other API, for example api/2/dashboard, but received this:
Response: {"startAt":0,"maxResults":20,"total":0,"dashboards":[]}
Using api/2/myself i received this:
Response: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>401</status-code><message>Client must be authenticated to access this resource.</message></status>
Maybe i missed something and project can be invisible? But for basic authorization i'm using administrator login and password.
Finally figured it out!
I did two mistakes:
http is wrong, https is right!
emailAndPasswordAsb64String was created using email and password, it's wrong! User should type in username instead of email! For administrator account username is admin by default.
Hope this will help someone!

Resources