I am using calling feature in App . Problem is that if no sim card installed in device then "No sim card installed" Alert view showing 2 times . I am using this code :
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:phoneNumber]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
}
Note: 1st Alert view automatically hide and again 2nd one is appearing .
Finally Found alternate solution for this :
Actually this is not an issue , This is transition effect :
To resolve it i have integrated below code before calling feature :
#import CoreTelephony;
CTTelephonyNetworkInfo *networkInfo = [CTTelephonyNetworkInfo new];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (!carrier.isoCountryCode) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No SIM Card Installed" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
}
import UIKit
import Alamofire
import NVActivityIndicatorView
import Reachability
//pod 'NVActivityIndicatorView'
//pod 'Alamofire', '~> 4.0'
//pod 'ReachabilitySwift'
typealias CompletionHandler = (_ success:Bool,_ reponsedata:Data) -> Void
typealias CompletionHandlerJson = (_ success:Bool,_ reponsedata:NSMutableDictionary) -> Void
typealias ResponseHandler = (_ success:Bool,_ data:NSData, _ error : String) -> Void
typealias ConnectivityHandler = (_ success:Bool) -> Void
class Connectivity {
class func internetConnection(completionHandler: #escaping ConnectivityHandler) {
//var Status:Bool = false
let url = NSURL(string: "http://google.com/")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "HEAD"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 1.0
let session = URLSession.shared
session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
completionHandler(true)
}
}
completionHandler(false)
}).resume()
}
class func connetivityAvailable() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
class WebserviceHelper: NSObject {
class func postWebServiceCall(urlString:String, parameters:[String:AnyObject], encodingType: String, ShowProgress:Bool, completionHandler: #escaping CompletionHandler){
if Connectivity.connetivityAvailable() == false {
log(message: "internet is not available.")
HUD.hide()
AppDelegate.showMessage(message:NO_INTERNET_AVAILABLE)
completionHandler(false,Data())
return
}
if ShowProgress {
HUD.show(.systemActivity)
}
log(message: "\(urlString): + parametersnew")
let encoding: ParameterEncoding!
if encodingType == DefaultEncoding{
encoding = JSONEncoding.default
}else{
encoding = URLEncoding.httpBody
}
Alamofire.request(urlString, method: HTTPMethod.post, parameters: parameters, encoding: encoding , headers: HelperClass.sharedInstance.getApiHeader()).responseData(completionHandler: { (response) in
if response.result.isSuccess {
if ShowProgress {
HUD.hide()
}
if let result = response.result.value {
completionHandler(true,result)
}
}
if response.result.isFailure {
if ShowProgress{
HUD.hide()
}
print("Lost Connection %#",urlString)
if let responseCode = response.response?.statusCode as Int?{
print("Lost Connection with code %#",response.result.value as Any)
let responseDic = NSMutableDictionary()
responseDic.setObject(responseCode, forKey: "statusCode" as NSCopying)
completionHandler(false,Data())
}
completionHandler(false,Data())
}
})
}
class func postWebServiceJson(urlString:String, parameters:[String:AnyObject], encodingType: String, ShowProgress:Bool, completionHandler: #escaping CompletionHandlerJson){
if Connectivity.connetivityAvailable() == false {
AppDelegate.showMessage(message:NO_INTERNET_AVAILABLE)
completionHandler(false,NSMutableDictionary())
return
}
if ShowProgress {
HUD.show(.systemActivity)
}
log(message: "\(urlString): + parametersnew")
let encoding: ParameterEncoding!
if encodingType == DefaultEncoding{
encoding = JSONEncoding.default
}else{
encoding = URLEncoding.httpBody
}
Alamofire.request(urlString, method: HTTPMethod.post, parameters: parameters, encoding: encoding , headers: HelperClass.sharedInstance.getApiHeader()).responseJSON { (response) in
if response.result.isSuccess {
if ShowProgress {
HUD.hide()
}
if let result = response.result.value as? NSDictionary {
completionHandler(true,NSMutableDictionary(dictionary: result))
}
}
if response.result.isFailure {
if ShowProgress{
HUD.hide()
}
print("Lost Connection %#",urlString)
if let responseCode = response.response?.statusCode as Int?{
print("Lost Connection with code %#",response.result.value as Any)
let responseDic = NSMutableDictionary()
responseDic.setObject(responseCode, forKey: "statusCode" as NSCopying)
completionHandler(false,NSMutableDictionary())
}
completionHandler(false,NSMutableDictionary())
}
}
}
class func WebapiGetMethod(strurl:String, ShowProgress: Bool = false, completionHandler: #escaping CompletionHandlerJson){
if Connectivity.connetivityAvailable() == false {
log(message:"internet is not available.")
completionHandler(false,NSMutableDictionary())
//.. AppDelegate .showMessage(message:"Please check your internet connection")
return
}
if ShowProgress{
HUD.show(.systemActivity)
}
Alamofire.request(strurl).responseJSON { response in
if let status = response.response?.statusCode {
switch(status){
case 200:
if let result = response.result.value {
if let JSONdict = result as? NSMutableDictionary{
DispatchQueue.main.async {
completionHandler(true,JSONdict)
}
}
if ShowProgress {
HUD.hide()
}
}else{
if ShowProgress {
HUD.hide()
}
completionHandler(false,NSMutableDictionary())
}
log(message:"example success")
default:
log(message:"error with get response status: \(status)")
DispatchQueue.main.async {
if ShowProgress {
HUD.hide()
}
}
completionHandler(false,NSMutableDictionary())
}
}
DispatchQueue.main.async {
if ShowProgress {
HUD.hide()
}
}
}
}
class func getWebServiceCall(urlString:String,ShowProgress:Bool, completionHandler: #escaping CompletionHandler){
if Connectivity.connetivityAvailable() == false {
log(message: "internet is not available.")
HUD.hide()
AppDelegate.showMessage(message:NO_INTERNET_AVAILABLE)
completionHandler(false,Data())
return
}
if ShowProgress {
HUD.show(.systemActivity)
}
log(message: "\(urlString): + parametersnew")
Alamofire.request(urlString, method: .get, parameters: nil, encoding: URLEncoding.methodDependent, headers: HelperClass.sharedInstance.getApiHeader()).responseData { (response) in
if response.result.isSuccess {
if ShowProgress {
HUD.hide()
}
if let result = response.result.value {
completionHandler(true,result)
}
}
if response.result.isFailure {
if ShowProgress{
HUD.hide()
}
print("Lost Connection %#",urlString)
if let responseCode = response.response?.statusCode as Int?{
print("Lost Connection with code %#",response.result.value as Any)
let responseDic = NSMutableDictionary()
responseDic.setObject(responseCode, forKey: "statusCode" as NSCopying)
completionHandler(false,Data())
}
completionHandler(false,Data())
}
}
}
}
Related
i am facing problem to give provider name because i dont know how to give proper provider in swifter.authorize
my controller is where i am using login code
you can check func actiontwitter in which i have used provider then please suggest me how to use provider as parameter
i have installed swifter package in project
//
// twitterVc.swift
// socialLogin
//
// Created by ios on 19/11/22.
//
import UIKit
import FirebaseAuth
import Swifter
import SafariServices
struct TwitterConstants {
static let CONSUMER_KEY = "MY_CONSUMER_KEY"
static let CONSUMER_SECRET_KEY = "MY_CONSUMER_SECRET_KEY"
static let CALLBACK_URL = "MY_CALLBACK_URL"
}
class twitterVc: UIViewController {
var swifter: Swifter!
var accToken: Credential.OAuthAccessToken?
#IBOutlet weak var submitBtn: UIButton!
var provider = OAuthProvider(providerID: "twitter.com")
override func viewDidLoad() {
super.viewDidLoad()
self.isLoggedIn { loggedin in
if loggedin {
// Show the ViewController with the logged in user
print("Logged In?: YES")
} else {
// Show the Home ViewController
print("Logged In?: NO")
}
}
}
func isLoggedIn(completion: #escaping (Bool) -> ()) {
let userDefaults = UserDefaults.standard
let accessToken = userDefaults.string(forKey: "oauth_token") ?? ""
let accessTokenSecret = userDefaults.string(forKey: "oauth_token_secret") ?? ""
let swifter = Swifter(consumerKey: TwitterConstants.CONSUMER_KEY, consumerSecret: TwitterConstants.CONSUMER_SECRET_KEY, oauthToken: accessToken, oauthTokenSecret: accessTokenSecret)
swifter.verifyAccountCredentials(includeEntities: false, skipStatus: false, includeEmail: true, success: { _ in
// Verify Succeed - Access Token is valid
completion(true)
}) { _ in
// Verify Failed - Access Token has expired
completion(false)
}
}
#IBAction func actionSubmit(_ sender: Any) {
self.actionTwitter()
}
func actionTwitter(){
//~~~~~~~~~~~~~~problem is here it is not taking provider as parameter
self.swifter.authorize(withProvider: provider as! ASWebAuthenticationPresentationContextProviding, callbackURL: URL(string: TwitterConstants.CALLBACK_URL)!) { (tokan: Credential.OAuthAccessToken?, resp: URLResponse) in
}
}
}
func failureHandler(){
}
extension twitterVc: SFSafariViewControllerDelegate{
func getUserProfile() {
self.swifter.verifyAccountCredentials(includeEntities: false, skipStatus: false, includeEmail: true, success: { json in
let userDefaults = UserDefaults.standard
userDefaults.set(self.accToken?.key, forKey: "oauth_token")
userDefaults.set(self.accToken?.secret, forKey: "oauth_token_secret")
// Twitter Id
if let twitterId = json["id_str"].string {
print("Twitter Id: \(twitterId)")
} else {
// self.twitterId = "Not exists"
}
// Twitter Handle
if let twitterHandle = json["screen_name"].string {
print("Twitter Handle: \(twitterHandle)")
} else {
// self.twitterHandle = "Not exists"
}
// Twitter Name
if let twitterName = json["name"].string {
print("Twitter Name: \(twitterName)")
} else {
// self.twitterName = "Not exists"
}
// Twitter Email
if let twitterEmail = json["email"].string {
print("Twitter Email: \(twitterEmail)")
} else {
// self.twitterEmail = "Not exists"
}
// Twitter Profile Pic URL
if let twitterProfilePic = json["profile_image_url_https"].string?.replacingOccurrences(of: "_normal", with: "", options: .literal, range: nil) {
print("Twitter Profile URL: \(twitterProfilePic)")
} else {
// self.twitterProfilePicURL = "Not exists"
}
print("Twitter Access Token: \(self.accToken?.key ?? "Not exists")")
}) { error in
print("ERROR: \(error.localizedDescription)")
}
}
}
This is Doc File Generate in Postman by write method and url "link/services.php".
This is Header File.
#Headers({"Content-Type: application/json"})
#POST("services.php")
Observable<Division> divisionListApi(#Body HashMap<String, String> map);
map.put("method", "My_List");
After Postman Generation I Got This Given Below.
{"err_code":9,
"message":"My List ",
"list":[
{"ForestDivision":"Yam(T)"},
{"ForestDivision":"Rewar(T)"},
{"ForestDivision":"Ro(T)"},
{"ForestDivision":"Bh(T)"},
{"ForestDivision":"Ka(T) "},
{"ForestDivision":"Ambal(T) "},
{"ForestDivision":"Fari(T)"}]
}
I have made request by taking post mehod, is this the right way to create code in
swiftui.
import Foundation
import Combine
struct File: Decodable, Hashable {
var error_code : Int
var message : String
var list : [lisst]
}
struct lisst: Decodable, Hashable {
var ForestDivision: String
}
class fetchResults : ObservableObject{
#Published var fetchedRes : [lisst]?
func getData(completion: #escaping (File) -> ()){
print("Fetch")
let parameters = "{ I dont Know }"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string:
"URl")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { (data, _, _) in
let resultList = try! JSONDecoder().decode(File.self, from: data!)
print(" ")
print("ID: \(resultList.error_code)")
print("VOLUME: \(resultList.message)")
print("READINGS: \(String(describing: resultList.list))")
print(" ")
print("SUCCESS: Got data - \(data! )")
DispatchQueue.main.async {
completion(resultList) // << here !!
}
}
task.resume()
}
}
Also How to Write in Swiftui View.
To Make Properly Works in List View.
import SwiftUI
import UIKit
struct DivisionList: View {
#ObservedObject var res = fetchResults()
var body: some View {
NavigationView {
Text("Nothing Here")
List(res.fetchedRes ?? [], id: \.self) { resp in // Error Here
ForEach(res.list, id: \.self) { course in
VStack {
Text(res.for) // Error Here
}
}
}
.navigationBarTitle("Data")
.onAppear(perform: {
self.getData // Error Here
})
}
}
}
struct DivisionList_Previews: PreviewProvider {
static var previews: some View {
DivisionList()
}
}
Create New Swift File Copy this Post Requests.
import Foundation
import Combine
let postUrl = "Your URl"
struct divisionList: Decodable, Identifiable {
let id: Int
let mesg: String
let list: [FDivision]
private enum CodingKeys: String, CodingKey {
case id = "err_code"
case mesg = "message"
case list = "list"
}
}
struct FDivision: Decodable, Hashable {
let forestDivision: String
private enum CodingKeys: String, CodingKey {
case forestDivision = "ForestDivision"
}
init(data:String) {
forestDivision = data
}
}
class viewModal: ObservableObject {
#Published var items = [FDivision]()
func postData() {
guard let serviceUrl = URL(string: postUrl) else { return }
let parameters: [String: Any] = [
"method": "Your Method Name"
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
request.timeoutInterval = 20
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let dictionary = json as? [String:Any] {
if let arrList = dictionary["list"] as? [[String:Any]]{
for data in arrList{
let model = FDivision(data: data["ForestDivision"] as! String)
self.items.append(model)
}
}
}
print(json)
} catch {
print(error)
}
}
}.resume()
}
}
Create Now New Swiftui File.
import SwiftUI
import UIKit
struct DivisionList: View {
#ObservedObject var vm = viewModal()
var body: some View {
NavigationView {
VStack {
List(vm.items, id: \.self) { item in
Button(action: {}, label: {
Text(item.forestDivision).foregroundColor(.customGreen)
})
}
}.navigationBarTitle("Data")
.onAppear(perform: {
vm.postData()
})
}
}
}
struct DivisionList_Previews: PreviewProvider {
static var previews: some View {
DivisionList()
}
}
I have some difficulty using Combine in SwiftUI with making an API request and then decoding the data and returning it. When calling the API Service, it states in the 'AnyPublisher<UserLoginResponse, APIError>' that the result will be of such type. However, I would want to reuse the API Service and decode the response to different model structures. How can I call the API Service while defining which data structure it has to decode the returned data to? For example, in another ViewModel I would want to decode the API data to a 'NewsUpdatesResponse' instead of 'UserLoginResponse'. The code I have now is as follows:
Most code comes from: tundsdev
API Service
struct APIService {
func request(from endpoint: APIRequest, body: String) -> AnyPublisher<UserLoginResponse, APIError> {
var request = endpoint.urlRequest
request.httpMethod = endpoint.method
if endpoint.authenticated == true {
request.setValue("testToken", forHTTPHeaderField: "token")
}
if body != "" {
let finalBody = body.data(using: .utf8)
request.httpBody = finalBody
}
return URLSession
.shared
.dataTaskPublisher(for: request)
.receive(on: DispatchQueue.main)
.mapError { _ in APIError.unknown}
.flatMap { data, response -> AnyPublisher<UserLoginResponse, APIError> in
guard let response = response as? HTTPURLResponse else {
return Fail(error: APIError.unknown).eraseToAnyPublisher()
}
print(response.statusCode)
if response.statusCode == 200 {
let jsonDecoder = JSONDecoder()
return Just(data)
.decode(type: UserLoginResponse.self, decoder: jsonDecoder)
.mapError { _ in APIError.decodingError }
.eraseToAnyPublisher()
}
else {
return Fail(error: APIError.errorCode(response.statusCode)).eraseToAnyPublisher()
}
}
.eraseToAnyPublisher()
}
}
Login ViewModel
class LoginViewModel: ObservableObject {
#Published var loginState: ResultState = .loading
private var cancellables = Set<AnyCancellable>()
private let service: APIService
init(service: APIService) {
self.service = service
}
func login(username: String, password: String) {
self.loginState = .loading
let cancellable = service
.request(from: .login, body: "username=admin&password=admin")
.sink { res in
print(res)
switch res {
case .finished:
self.loginState = .success
case .failure(let error):
self.loginState = .failed(error: error)
}
} receiveValue: { response in
print(response)
}
self.cancellables.insert(cancellable)
}
}
the following is untested, but you could try something along this line, using generic Decodable:
struct APIService {
func request<T: Decodable>(from endpoint: APIRequest, body: String) -> AnyPublisher<T, APIError> {
var request = endpoint.urlRequest
request.httpMethod = endpoint.method
if endpoint.authenticated == true {
request.setValue("testToken", forHTTPHeaderField: "token")
}
if body != "" {
let finalBody = body.data(using: .utf8)
request.httpBody = finalBody
}
return URLSession
.shared
.dataTaskPublisher(for: request)
.receive(on: DispatchQueue.main)
.mapError { _ in APIError.unknown}
.flatMap { data, response -> AnyPublisher<T, APIError> in // <-- here
guard let response = response as? HTTPURLResponse else {
return Fail(error: APIError.unknown).eraseToAnyPublisher()
}
print(response.statusCode)
if response.statusCode == 200 {
let jsonDecoder = JSONDecoder()
return Just(data)
.decode(type: T.self, decoder: jsonDecoder) // <-- here
.mapError { _ in APIError.decodingError }
.eraseToAnyPublisher()
}
else {
return Fail(error: APIError.errorCode(response.statusCode)).eraseToAnyPublisher()
}
}
.eraseToAnyPublisher()
}
}
you may also want to return an array of such Decodable:
func requestThem<T: Decodable>(from endpoint: APIRequest, body: String) -> AnyPublisher<[T], APIError> {
....
.flatMap { data, response -> AnyPublisher<[T], APIError> in
...
.decode(type: [T].self, decoder: jsonDecoder)
...
The final solution which worked for me was the following with the help of workingdog.
API Service
struct APIService {
func request<T: Decodable>(ofType type: T.Type, from endpoint: APIRequest, body: String) -> AnyPublisher<T, Error> {
var request = endpoint.urlRequest
request.httpMethod = endpoint.method
if endpoint.authenticated == true {
request.setValue("testToken", forHTTPHeaderField: "token")
}
if body != "" {
let finalBody = body.data(using: .utf8)
request.httpBody = finalBody
}
return URLSession
.shared
.dataTaskPublisher(for: request)
.receive(on: DispatchQueue.main)
.mapError { _ in Error.unknown}
.flatMap { data, response -> AnyPublisher<T, Error> in
guard let response = response as? HTTPURLResponse else {
return Fail(error: Error.unknown).eraseToAnyPublisher()
}
print(response.statusCode)
let jsonDecoder = JSONDecoder()
if response.statusCode == 200 {
return Just(data)
.decode(type: T.self, decoder: jsonDecoder)
.mapError { _ in Error.decodingError }
.eraseToAnyPublisher()
}
else {
do {
let errorMessage = try jsonDecoder.decode(APIErrorMessage.self, from: data)
return Fail(error: Error.errorCode(statusCode: response.statusCode, errorMessage: errorMessage.error ?? "Er is iets foutgegaan")).eraseToAnyPublisher()
}
catch {
return Fail(error: Error.decodingError).eraseToAnyPublisher()
}
}
}
.eraseToAnyPublisher()
}
}
Login ViewModel
class LoginViewModel: ObservableObject {
#Published var loginState: ResultState = .loading
private var cancellables = Set<AnyCancellable>()
private let service: APIService
init(service: APIService) {
self.service = service
}
func login(username: String, password: String) {
self.loginState = .loading
let preparedBody = APIPrepper.prepBody(parametersDict: ["username": username, "password": password])
let cancellable = service.request(ofType: UserLoginResponse.self, from: .login, body: preparedBody).sink { res in
switch res {
case .finished:
self.loginState = .success
print(self.loginState)
case .failure(let error):
self.loginState = .failed(stateIdentifier: error.statusCode, errorMessage: error.errorMessage)
print(self.loginState)
}
} receiveValue: { response in
print(response)
}
self.cancellables.insert(cancellable)
}
}
Note that I have made some minor changes to the passing of the username and password parameters in the meantime.
For a recent project I tried to pull some data from a server in the SOAP and oData format respectively, that is protected with a Microsoft NTLM authentication, and it has been a nightmare figuring out how to do it, none of the online examples really worked.
So here is my solution; I had to adapt, expand and combine a few different sources. I hope this helps someone in the future.
You might have to allow arbitrary loads!!
Adapted from:
https://gist.github.com/stevenschobert/f374c999e5cba6ccf09653b846967c83
https://blogs.msdn.microsoft.com/chiranth/2013/09/20/ntlm-want-to-know-how-it-works/
import UIKit
class ViewController: UIViewController {
var username: String? = nil
var password: String? = nil
lazy var conn: URLSession = {
let config = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
return session
}()
override func viewDidLoad() {
super.viewDidLoad()
username = "<username>"
password = "<password>"
ntlm()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func ntlm() {
let urlString = "<url>"
let url = URL(string: urlString)
let request = NSMutableURLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60000)
request.httpMethod = "GET"
let task = conn.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
print(response)
print(error)
print(String(data: data!, encoding: .utf8))
})
task.resume()
}
func doesHaveCredentials() -> Bool {
guard let _ = self.username else { return false }
guard let _ = self.password else { return false }
return true
}
}
extension ViewController: URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("got challenge")
guard challenge.previousFailureCount == 0 else {
print("too many failures")
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM else {
print("unknown authentication method \(challenge.protectionSpace.authenticationMethod)")
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
guard self.doesHaveCredentials() else {
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
DispatchQueue.main.async {
print("Userdata not set")
};
return
}
let credentials = URLCredential(user: self.username!, password: self.password!, persistence: .forSession)
challenge.sender?.use(credentials, for: challenge)
completionHandler(.useCredential, credentials)
}
}
I want to parse json from java spring code (Xcode 7.3 / Swift). I tried almost every solution from all sites.
When I register it gives the following error message at the console:
Response = Optional(<NSHTTPURLResponse: 0x7a7607e0> { URL: http://www.____.com/saveRegistrationJson.htm } { status code: 405, headers {
Allow = GET;
Connection = "Keep-Alive";
"Content-Length" = 1089;
"Content-Type" = "text/html;charset=utf-8";
Date = "Wed, 04 May 2016 12:21:34 GMT";
"Keep-Alive" = "timeout=15, max=100";
Server = "Apache-Coyote/1.1";
} })
before json
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
This is my Code:
import UIKit
class RegistrationViewController: UIViewController {
#IBOutlet weak var userfnametextfield: UITextField!
#IBOutlet weak var userlnametextfield: UITextField!
#IBOutlet weak var useremailtextfield: UITextField!
#IBOutlet weak var userpwdtextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func RegisterbtnTapped(sender: AnyObject) {
let fname = userfnametextfield.text
let lname = userlnametextfield.text
let Email = useremailtextfield.text
let pwd = userpwdtextfield.text
//check empty fields
if(fname!.isEmpty || lname!.isEmpty || Email!.isEmpty || pwd!.isEmpty )
{
DisplayMyAlertMessage("All Fields are required")
return
}
//store data
NSUserDefaults.standardUserDefaults().setObject(fname, forKey: "fname")
NSUserDefaults.standardUserDefaults().setObject(lname, forKey: "lname")
NSUserDefaults.standardUserDefaults().setObject(Email, forKey: "Email")
NSUserDefaults.standardUserDefaults().setObject(pwd, forKey: "password")
NSUserDefaults.standardUserDefaults().synchronize()
//send user data to server side
let myurl = NSURL(string: "http://www.____.com/saveRegistrationJson.htm")
let request = NSMutableURLRequest(URL: myurl!)
request.HTTPMethod = "POST"
let poststring = "fname\(fname!)&lname\(lname!)&email\(Email!)&password\(pwd!)"
request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding)
//request.HTTPBody = postData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data,response, error in
if error != nil{
print("Error\(error)")
return
}
print("Response = \(response)")
do{
var err : NSError?
print("before json")
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
print(json)
print("After json")
//print("demo : \(response?.description)")
guard let parseJSON = json else{
print("parsing json here:")
return
}
// guard let value = NSString(data: data!, encoding: NSUTF8StringEncoding) else{
// print("parsed")
// return
//}
//print("FirstName\(value)")
var requestValue = parseJSON[" "] as? String
print("result:\(requestValue)")
var isUserRegistered:Bool = false
if(requestValue=="Success") { isUserRegistered = true}
var messageToDisplay:String = parseJSON["Success"] as! String
if(!isUserRegistered){
messageToDisplay = parseJSON[" "] as! String
}
dispatch_async(dispatch_get_main_queue(), {
let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let onAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (ACTION) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(onAction)
self.presentViewController(myAlert, animated: true, completion: nil)
})
}
catch let error as NSError
{
print(error)
}
}
task.resume()
Help is very appreciated.