it is possible to post parameters for register? - swift3

i try to use the URLRequest for post Parameters (user name , password ) for some website from iOS (swift language) and the operation is success and i receive message success from the web which tell me you are logged in
below it's my code :
// check the user name and password
guard let url = URL(string: "http://MyWeb/login.php")else {
displayAlertControllerForLogin(title: "Wrong URL", message: "Please Check URL")
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let postString = "username=\(userName)&password=\(password)"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: urlRequest) {[weak self] (data, response, error) in
if error != nil {
print("have an error")
return
}// end the if error
let string = String(data: data!, encoding: .utf8)
if let string = string {
if string.contains("cel_song") {
DispatchQueue.main.async { [weak self] in
// present main view for check only
let tabBarController = MainVC()
self?.present(tabBarController, animated: true, completion: nil)
}// end the dispatch
}else{
// show the alert if the user invalid
DispatchQueue.main.async { [weak self] in
self?.displayAlertControllerForLogin(title: "Error Login!", message: "Please Check User Name / Password")
}// end the dispatch
}// end the else
}// end the if let string
}// end the task
task.resume()
now please i need to register to this web site through the post 5 parameters using URLrequest (username , full name ,email, website,password,confirmPassword) to register in that website
but the operation is failed
the below is my code for register in website using urlRequest post :
guard let url = URL(string: "http://MyWeb/register.php") else {displayAlertControllerForLogin(title: "Wrong URL", message: "Please ReWrite URL") ; return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let webSite = "google"
let postString = "username=\(userName)&fullname=\(fullName)&email=\(email)&website=\(webSite)&password=\(password)&confirmPassword=\(confirmPassword)"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: urlRequest, completionHandler: {[weak self] (data, response, error) in
if let error = error {
self?.displayAlertControllerForLogin(title: "Error Issue", message: error.localizedDescription)
return
}
// fetch the data
let string = String(data: data!, encoding: .utf8)
if let string = string {
if string.contains("Registration...") {
// register faield
DispatchQueue.main.async { [weak self] in
self?.displayAlertControllerForLogin(title: "Register Faield!", message: "Some Issue Occur When Try To register!")
print(string)
return
}
}else{
// register complete
DispatchQueue.main.async { [weak self] in
self?.displayAlertControllerForLogin(title: "Register Complete!", message: "Welcome \(userName) You Are Register To Ampache Successfully!")
return
}
}// end the if string.contains
}// end the if let
})// end the task
task.resume()
my question please it's possible to register to some website using url request with post 5 parameters in swift language?

Related

While implementing the MSAL Authentication, not able to make the Graph API Call

I am trying to make a Graph API call after getting the access token but not able to make the graph API call function.
Facing the error in calling the function, actually I don't have an idea about the HTTP response but I need a user credentials for login and the logout functions, if suppose I got a user credentials means I have to send the data's from login function to logout function.
struct FieldUIViewRepresentable : UIViewControllerRepresentable{
func makeUIViewController(context: Context) -> some UIViewController {
let log = loginviewcontroller()
return log
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}
class loginviewcontroller : UIViewController,UIWindowSceneDelegate{
var lableText : String = "default Login"
var account : MSALAccount? = nil
let kAuthority = "https://login.microsoftonline.com/common"
let kGraphEndpoint = "https://graph.microsoft.com/"
var accessToken : String = ""
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 60))
button.setTitle("Login click", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .blue
button.addTarget(self, action: #selector(login), for: .touchUpInside)
self.view.addSubview(button)
let button2 = UIButton(frame: CGRect(x: 100, y: 180, width: 200, height: 60))
button2.setTitle("Logout", for: .normal)
button2.setTitleColor(.white, for: .normal)
button2.backgroundColor = .red
button2.addTarget(self, action: #selector(logout), for: .touchUpInside)
self.view.addSubview(button2)
}
#objc func login(){
let config = MSALPublicClientApplicationConfig(clientId: "0f166c0f-55e1-4de1-b6fe-e0c35c331f4b")
let scopes = [""]
if let application = try? MSALPublicClientApplication(configuration: config) {
let viewController = self
let webviewParameters = MSALWebviewParameters(authPresentationViewController: viewController)
let interactiveParameters = MSALInteractiveTokenParameters(scopes: scopes, webviewParameters: webviewParameters)
application.acquireToken(with: interactiveParameters, completionBlock: { (result, error) in
guard let authResult = result, error == nil else {
print("The auth result is \(error!)")
print("Auth result localized error \(error!.localizedDescription)")
return
}
print("Auth Result is \(authResult.account)")
self.account = authResult.account
let accessToken = authResult.accessToken
self.accessToken = accessToken
self.getContentWithToken()
print("The access token is \(accessToken)")
let accountIdentifier = authResult.account.identifier
print("Account Identifier \(String(describing: accountIdentifier))")
})
}
else {
print("Unable to create application.")
}
}
func getContentWithToken() {
print("get content with token function invokes")
// Specify the Graph API endpoint
let graphURI = getGraphEndpoint()
let url = URL(string: graphURI)
var request = URLRequest(url: url!)
request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
return
}
guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else {
return
}
}.resume()
}
func getGraphEndpoint() -> String {
return kGraphEndpoint.hasSuffix("/") ? (kGraphEndpoint + "v1.0/me/") : (kGraphEndpoint + "/v1.0/me/");
}
#objc func logout(){
let account = self.account ?? nil //* account retrieved above
let config = MSALPublicClientApplicationConfig(clientId: "0f166c0f-55e1-4de1-b6fe-e0c35c331f4b")
let scopes = [""]
let application = try? MSALPublicClientApplication(configuration: config)
let viewController = self
let webviewParameters = MSALWebviewParameters(authPresentationViewController: viewController)
let signoutParameters = MSALSignoutParameters(webviewParameters: webviewParameters)
signoutParameters.signoutFromBrowser = false
application?.signout(with: account!, signoutParameters: signoutParameters, completionBlock: {(success, error) in
if let error = error {
// Signout failed
return
}
print("Signout is Completed")
// Sign out completed successfully
})
}
}

unable to save the data in api using POST method in swift

I am not able to see the changes as per required in API, when I am using the Post method to do so can I get the correct solution. Here is the Code that I have written
#IBAction func savebutton(_ sender: Any) {
if let id1 = UserDefaults.standard.string(forKey: "Userid"),let usertype1 = UserDefaults.standard.string(forKey: "Usertype")
{
var request = URLRequest(url: URL(string: "http://www.shreetechnosolution.com/funded/donorprofile.php")!)
request.httpMethod = "POST"
let postString = "Name=\(textname.text!)&Gender=\(textGender.text!)&Email=\(textemail.text!)&MobileNo=\(textmb.text!)&Country=\(textcountry.text!)&donorid=\(id1)&usertype=\(usertype1)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
let msg = json.value(forKey: "message") as! NSString!
let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
}
Can anyone help me, please?

Trying to Reload FSCalendar with JSon data but it crashes

this question is linked with the my previous account's question.
How to make API call for this web service to fetch array of present and absent dates separately in swift?
code
import UIKit
import FSCalendar
class AttendenceViewController : UIViewController, FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance
{
#IBOutlet weak var calendar: FSCalendar!
var presentdays : Array = [String]()
var absentdays : Array = [String]()
fileprivate let gregorian: Calendar = Calendar(identifier: .gregorian)
fileprivate lazy var dateFormatter1: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
fileprivate lazy var dateFormatter2: DateFormatter = {
let formatter2 = DateFormatter()
formatter2.dateFormat = "dd"
return formatter2
}()
override func viewDidLoad() {
super.viewDidLoad()
self.getdateFromJSON()
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillDefaultColorFor date: Date) -> UIColor? {
let datestring2 : String = dateFormatter1.string(from: date)
if presentdays.contains(datestring2)
{
return UIColor.green
}
else if absentdays.contains(datestring2)
{
return UIColor.red
}
else
{
return nil
}
}
func getdateFromJSON()
{
let url = NSURL(string: "ezschoolportalapi.azurewebsites.net/api/Student/AttendanceDetails?schoolid=1&studentid=2&month=6&year=2017")
let request = NSMutableURLRequest(url: url! as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error)
in
guard error == nil && data != nil else
{
print("Error:",error)
return
}
let httpstatus = response as? HTTPURLResponse
if httpstatus?.statusCode == 200
{
if data?.count != 0
{
if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? [String:Any],
let presentdetails = responseJSON["Present"] as? [[String:Any]],
let Absentdetails = responseJSON["Absent"] as? [[String:Any]] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.presentdays = presentdetails.flatMap { dateFormatter.date(from: $0["Date"] as! String) }.flatMap {
self.dateFormatter2.string(from:$0)
}
self.absentdays = Absentdetails.flatMap { dateFormatter.date(from: $0["Date"] as! String) }.flatMap { self.dateFormatter2.string(from:$0) }
DispatchQueue.main.async
{
self.calendar.reloadData()
}
}
}
else
{
print("No data got from URL")
}
}
else{
print("error httpstatus code is :",httpstatus?.statusCode)
}
}
task.resume()
}
}
I'm attaching the error log here please help thanks in advance.
ERROR LOG
2017-06-17 10:23:50.671 ezSchool[1848:24475]
-[UICachedDeviceWhiteColor unsignedLongLongValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.672
ezSchool[1848:24475] Failed to set (placeholderType) user defined
inspected property on (FSCalendar): -[UICachedDeviceWhiteColor
unsignedLongLongValue]: unrecognized selector sent to instance
0x608000059ec0 2017-06-17 10:23:50.672 ezSchool[1848:24475]
-[UICachedDeviceWhiteColor unsignedLongLongValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.672
ezSchool[1848:24475] Failed to set (firstWeekday) user defined
inspected property on (FSCalendar): -[UICachedDeviceWhiteColor
unsignedLongLongValue]: unrecognized selector sent to instance
0x608000059ec0 2017-06-17 10:23:50.672 ezSchool[1848:24475]
-[UICachedDeviceWhiteColor doubleValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.673 ezSchool[1848:24475]
Failed to set (headerHeight) user defined inspected property on
(FSCalendar): -[UICachedDeviceWhiteColor doubleValue]: unrecognized
selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.673
ezSchool[1848:24475] -[UICachedDeviceWhiteColor doubleValue]:
unrecognized selector sent to instance 0x608000059ec0 2017-06-17
10:23:50.673 ezSchool[1848:24475] Failed to set (headerTitleTextSize)
user defined inspected property on (FSCalendar):
-[UICachedDeviceWhiteColor doubleValue]: unrecognized selector sent to instance 0x608000059ec0
Replace the function getdateFromJSON() with
func getdateFromJSON()
{
let url = NSURL(string: "http://ezschoolportalapi.azurewebsites.net/api/Student/AttendanceDetails?schoolid=1&studentid=2&month=6&year=2017")
let request = NSMutableURLRequest(url: url! as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error)
in
guard error == nil && data != nil else
{
print("Error:",error ?? "error")
return
}
let httpstatus = response as? HTTPURLResponse
if httpstatus?.statusCode == 200
{
if data?.count != 0
{
if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? [String:Any],
let presentdetails = responseJSON["Present"] as? [[String:Any]],
let Absentdetails = responseJSON["Absent"] as? [[String:Any]] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.presentdays = presentdetails.flatMap { dateFormatter.date(from: $0["Date"] as! String) }.flatMap {
self.dateFormatter1.string(from:$0)
}
self.absentdays = Absentdetails.flatMap { dateFormatter.date(from: $0["Date"] as! String) }.flatMap { self.dateFormatter1.string(from:$0) }
DispatchQueue.main.async
{
self.calendar.reloadData()
}
}
}
else
{
print("No data got from URL")
}
}
else{
print("error httpstatus code is :",httpstatus?.statusCode ?? "5")
}
}
task.resume()
}
Please see whether the below attached image is your desired output

how to use nsurlsession data task in background mode swift 3

I want to run this code in app applicationDidEnterBackground mode. But app don't work in background mode (after press home button).
func request(urlreq : String,post :String?, completionHandler: #escaping (HTTPURLResponse?,JSON?) -> ()){
let url = NSURL(string: API_URL + urlreq )
let request = NSMutableURLRequest(url: url! as URL)
request.setValue(USER_AGENT, forHTTPHeaderField: "User-Agent")
request.httpMethod = "GET"
if(post != nil){
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = post!.data(using: String.Encoding.utf8)
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
session.dataTask(with: request as URLRequest, completionHandler: { (returnData, response, error) -> Void in
if(returnData != nil)
{
let json = JSON(data: (returnData as NSData!) as Data, error: nil)
completionHandler(response as? HTTPURLResponse,json)
}else{
completionHandler(response as? HTTPURLResponse,nil)
}
}).resume()
}

api youtube in swift 3 error 403

I am trying to use youtube api in ios swift, and following this tutorial
http://www.appcoda.com/youtube-api-ios-tutorial/
HTTP Status Code = 403
Error while loading channel details: nil
I'm using swift 3
var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(textField.text)&type=\(type)&key=\(apiKey)"
urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
// Create a NSURL object based on the above string.
let targetURL = URL(string: urlString)
// Get the results.
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
// Convert the JSON data to a dictionary object.
do {
let resultsDict = try JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<String, AnyObject>
// Get all search result items ("items" array).
let items: Array<Dictionary<String, AnyObject>> = resultsDict["items"] as! Array<Dictionary<String, AnyObject>>
// Loop through all search results and keep just the necessary data.
for i in 0 ..< items.count {
let snippetDict = items[i]["snippet"] as! Dictionary<String, AnyObject>
// Gather the proper data depending on whether we're searching for channels or for videos.
if self.segDisplayedContent.selectedSegmentIndex == 0 {
// Keep the channel ID.
self.desiredChannelsArray.append(snippetDict["channelId"] as! String)
}
else {
// Create a new dictionary to store the video details.
var videoDetailsDict = Dictionary<String, AnyObject>()
videoDetailsDict["title"] = snippetDict["title"]
videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<String, AnyObject>)["default"] as! Dictionary<String, AnyObject>)["url"]
videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<String, AnyObject>)["videoId"]
// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videosArray.append(videoDetailsDict)
// Reload the tableview.
self.tblVideos.reloadData()
}
}
} catch {
print(error)
}
// Call the getChannelDetails(…) function to fetch the channels.
if self.segDisplayedContent.selectedSegmentIndex == 0 {
self.getChannelDetails(true)
}
}
else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel videos: \(error)")
}
// Hide the activity indicator.
self.viewWait.isHidden = true
})
return true
}
// MARK: Custom method implementation
func performGetRequest(_ targetURL: URL!, completion: #escaping (_ data: Data?, _ HTTPStatusCode: Int, _ error: NSError?) -> Void) {
// let request = NSMutableURLRequest(url: targetURL)
// request.httpMethod = "GET"
var request = URLRequest(url: targetURL)
request.httpMethod = "GET"
let sessionConfiguration = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfiguration)
/* let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
completion(data, (response as! HTTPURLResponse).statusCode, error)
})
} as! (Data?, URLResponse?, Error?) -> Void)*/
/* let task = session.dataTask(with: request, completionHandler: ({ (data: Data?, response: URLResponse?, error: NSError?) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
completion(data as Data?, (response as! HTTPURLResponse).statusCode, error)
})
} as! (Data?, URLResponse?, Error?) -> Void))*/
let task = session.dataTask(with: request) { data, response, error in DispatchQueue.main.async { completion(data, (response as! HTTPURLResponse).statusCode, error as? NSError) } }
task.resume()
}
First of all the JSON dictionary representation in Swift 3 is [String:Any] (aka Dictionary<String,Any>)
Second of all in Swift 3 all parameter labels in closures have been removed
func performGetRequest(_ targetURL: URL, completion: #escaping (Data?, Int, NSError?) -> Void) {
Do not use implicit unwrapped optionals for method parameter types. Either use regular optional (?) or non-optional.
Error 403 means Forbidden Access. Make sure you have the correct apiKey from google/youtube developer.
I also used the appcoda youtube api tutorial (which is in Swift 2 I think) and this is a working version of mine for swift 3.
func getVideosForChannelAtIndex() {
let urlString = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=\(playlistID)&maxResults=\(maxResults)&key=\(apiKey)"
// Create a NSURL object based on the above string.
let targetURL = URL(string: urlString)
// Fetch the playlist from Google.
performGetRequest(targetURL!) { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
do {
self.videos = []
// Convert the JSON data into a dictionary.
let resultsDict = try JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<AnyHashable, Any>
// Get all playlist items ("items" array).
let items:Array<Dictionary<AnyHashable, Any>> = resultsDict["items"] as! Array<Dictionary<AnyHashable, Any>>
// Use a loop to go through all video items.
// for var i=0; i<items.count; ++i
for i in 0 ..< items.count {
let playlistSnippetDict = (items[i] as Dictionary<AnyHashable, Any>)["snippet"] as! Dictionary<AnyHashable, Any>
let video = Video()
video.title = playlistSnippetDict["title"] as? String
// video.thumbnail =
video.videoId = (playlistSnippetDict["resourceId"] as? Dictionary<AnyHashable, Any>)?["videoId"] as? String
guard let thumbnail = ((playlistSnippetDict["thumbnails"] as? Dictionary<AnyHashable, Any>)?["high"] as? Dictionary<AnyHashable, Any>)?["url"] as? String else {
video.thumbnail = UIImage(named: "Icon1024x1024")
return
}
guard let url:URL? = URL(string: thumbnail), let data:Data? = try? Data(contentsOf: url!) else {
video.thumbnail = UIImage(named: "Icon1024x1024")
return
}
if let dataImage = data {
video.thumbnail = UIImage(data: dataImage)
} else {
video.thumbnail = UIImage(named: "Icon1024x1024")
}
self.videos.append(video)
// Reload the tableview.
self.tblVideos.reloadData()
}
} catch {
print("json error: \(error)")
}
} else {
print("")
print("HTTP Status Code = \(HTTPStatusCode)")
print("")
//Show alertDialog here with Error
print("Error while loading videos: \(error?.localizedDescription)")
let alert = UIAlertView(title: "Oops!", message: error?.localizedDescription, delegate: self, cancelButtonTitle: "OK")
alert.show()
}
// Hide the activity indicator.
self.viewWait.isHidden = true
}
}
This is for the performGetRequest
func performGetRequest(_ targetURL: URL, completion: #escaping (_ data: Data?, _ HTTPStatusCode: Int?, _ error: Error?) -> Void) {
var request = URLRequest(url: targetURL)
request.httpMethod = "GET"
let sessionConfiguration = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfiguration)
let task = session.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
completion(data, (response as? HTTPURLResponse)?.statusCode, error)
})
}
task.resume()
}