I m unable to save the data back to json which is written in text fields and when save button is clicked it have to save the updated data to json.
Here is the code i have written on save button action:
if let id = UserDefaults.standard.string(forKey: "NgoId"){
var request = URLRequest(url: URL(string: "http://www.shreetechnosolution.com/funded/ngo_profile.php?ngoid=\(id)")!)
request.httpMethod = "POST"
let postString = "Nameofngo=\(textngoname.text!)&NameofChiefFunctionary=\(textcheiffunction.text!)&NameofChairman=\(textchairman.text!)&NameofSeceratary=\(textsecratary.text!)&NameofTreasurer=\(texttreasurer.text!)&ParentOrganization=\(textparentorg.text!)&AboutNGO=\(Textngo.text)&photoofNGO=\(imageviewngo.image)&ngoid=\(id)&value=NGO"
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=\(error ?? "" as! 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()
}
task.resume()
}
Try following way of post data code, this will help you. And always try use try-catch to get error. Below is your working code with response.
UserDefaults.standard.setValue(1, forKey: "NgoId");
if let id = UserDefaults.standard.string(forKey: "NgoId"){
var request = URLRequest(url: URL(string: "http://www.shreetechnosolution.com/funded/ngo_profile.php?ngoid=\(id)")!)
request.httpMethod = "POST"
var postJson = Dictionary<String, Any>.init();
postJson["Nameofngo"] = "NONAME";
postJson["NameofChiefFunctionary"] = "";
postJson["NameofChairman"] = "";
postJson["NameofSeceratary"] = "";
postJson["NameofTreasurer"] = "";
postJson["ParentOrganization"] = "";
postJson["AboutNGO"] = "";
postJson["ngoid"] = id;
postJson["value"] = "NGO";
print("post json \(postJson)");
do {
let postData = try JSONSerialization.data(withJSONObject: postJson, options: JSONSerialization.WritingOptions.prettyPrinted);
request.httpBody = postData;
}catch let err {
print("exception is \(err)");
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let responseData = data, error == nil else { // check for fundamental networking error
print("error=\(error ?? "" as! 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: responseData, options: []) as! NSDictionary
print("json response \(json)");
}
task.resume()
}
Response In log-----
{
listngoprofile = (
{
AboutNGO = "<null>";
City = "<null>";
CityofRegisteration = "<null>";
CompleteAddress = "<null>";
Country = "<null>";
DateofRegisteration = "<null>";
Declaration = 1;
EmailID = "hgmaetrust#gmail.com";
FCRADateofRegisteration = "";
FCRARegisterationNo = "";
FCRAValidUpto = "19/07/2025";
"Fax_No" = "<null>";
Issues = (
{
Issues = "Education& Scholarship";
},
{
Issues = fdfsdfasdfdsd;
},
{
Issues = kdjkdsksd;
},
{
Issues = dfjkkdf;
}
);
Majorachievements = "<null>";
MobileNo = 9922400698;
NGOBankAccountNo = "<null>";
NGOBankAccounttype = "<null>";
NGOBankIFSCCode = "<null>";
NameinBankAccount = "<null>";
NameofChairman = "<null>";
NameofChiefFunctionary = "<null>";
NameofSeceratary = "<null>";
NameofTreasurer = "<null>";
Nameofngo = "<null>";
NgoID = 1;
ParentOrganization = "<null>";
Pincode = "<null>";
Regcertimg = "<null>";
RegisterationNo = "<null>";
Registeredwith = "<null>";
State = "<null>";
StateofRegisteration = "<null>";
"TelePhone_No" = "<null>";
TypeofNGO = "<null>";
Validupto = "<null>";
WebsiteURL = "<null>";
YearofEstablishment = "<null>";
keyOperational = (
{
Area = Maharashtra;
},
{
Area = dfsdfdfsdfsdfdsfdsfdsfds;
},
{
Area = kjdjdkjdfjl;
},
{
Area = jldklk;
}
);
photoofNGO = "<null>";
}
);
success = 1;
}
If you want to apply check for <null> values in response, then follow below code for check.
if let successVal = response?["success"] as? NSNumber {
uWillGetValueHere = successVal;
}
Related
I'm trying to use Aws4RequestSigner in a VS2015 form to sign a search request to Amazon PAAPI.
https://www.nuget.org/packages/Aws4RequestSigner/
I get this response from the API:
{"__type":"com.amazon.paapi5#IncompleteSignatureException","Errors":[{"Code":"IncompleteSignature","Message":"The request signature did not include all of the required components. If you are using an AWS SDK, requests are signed for you automatically; otherwise, go to https://webservices.amazon.com/paapi5/documentation/sending-request.html#signing."}]}
private async void Form1_Load(object sender, EventArgs e)
{
_accessKey = "x";
_secretKey = "x";
_service = "ProductAdvertisingAPIv1";
_region = "us-east-1";
_requestUri = new Uri("https://webservices.amazon.com/paapi5/searchitems");
var payload = new
{
Keywords = "Harry",
Marketplace = "www.amazon.com",
PartnerTag = "x0d-20",
PartnerType = "Associates",
Resources = new string[] { "Images.Primary.Small", "ItemInfo.Title", "Offers.Listings.Price" },
SearchIndex = "All"
};
string jsonString = JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var xAmzDate = GetTimeStamp();
content.Headers.Add("content-encoding", "amz-1.0");
content.Headers.Add("x-amz-date", xAmzDate);
content.Headers.Add("x-amz-target", "com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems");
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = _requestUri,
Content = content
};
request.Headers.Host = "webservices.amazon.com";
var contentType = new MediaTypeHeaderValue("application/json");
contentType.CharSet = "utf-8";
request.Content.Headers.ContentType = contentType;
var signer = new AWS4RequestSigner(_accessKey, _secretKey);
request = await signer.Sign(request, _service, _region);
try
{
var client = new HttpClient();
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
}
// response.EnsureSuccessStatusCode();
txtDisplay.Text = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
string error = ex.Message;
txtDisplay.Text = error;
}
}
private string GetTimeStamp()
{
return DateTime.UtcNow.ToString("yyyyMMdd\\THHmmss\\Z");
}
It could be that the headers are being added incorrectly or Aws4RequestSigner is simply outdated.
Connection code
till yesterday everything working properly but now it giving the error to connect the json data.
...........................................................................................................................................................................................
class ProductDataStacture with ChangeNotifier {
List<Products> _products = [];
List<Banners> _banners = [];
List<Categories> _category = [];
List<Random> _random = [];
Future<bool> getProducts() async {
String url = 'https://shymee.com';
try {
// http.Response response = await http.get(Uri.parse(url + "/home"),
var response = await http.get(Uri.parse(url + "/home"), headers: {
'Authorization': 'token a867c3c092e8b1195f398ed5ca52dda4e5ff5ed8'
});
var data = json.decode(response.body);
print(data);
List<Products> prod = [];
List<Banners> bann = [];
List<Categories> cate = [];
List<Random> ran = [];
data['products'].forEach((element) {
Products product = Products.fromJson(element);
prod.add(product);
print("this is product ${product}");
});
data['banners'].forEach((element) {
Banners banner = Banners.fromJson(element);
bann.add(banner);
});
data['categories'].forEach((element) {
Categories category = Categories.fromJson(element);
cate.add(category);
});
data['random'].forEach((element) {
Random random = Random.fromJson(element);
ran.add(random);
});
_products = prod;
_banners = bann;
_category = cate;
_random = ran;
return true;
} catch (e) {
print("e getProducts");
print(e);
return false;
}
}
List<Products> get productsList {
return [..._products];
}
List<Banners> get bannersList {
return [..._banners];
}
List<Categories> get categoryList {
return [..._category];
}
List<Random> get randomList {
return [..._random];
}
}
Temporary you can solve this issue with below recommend
class MyHttpOverrides extends HttpOverrides{
#override
HttpClient createHttpClient(SecurityContext? context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int
port)=> true;
}
}
enter link description here
But my suggestion is you use valid certificate in server side
func reqAuth(serviceParams: AuthServiceParams) -> AnyPublisher<AuthResponse, Error> {
var subject = PassthroughSubject<Any,Error>()
AlamofireService.auth(serviceParams: serviceParams).responseObject { (response : DataResponse<AuthResponse>) in
if (response.error != nil ) {
print("❌⭕️❌ Auth login hatalı bir dönüş aldı sorun var.")
subject.send(response.error!)
return
} else {
if let data = response.result.value {
guard let token = data.data?.token else {
print("TOKEN BULUNAMADI")
let authResponse = AuthResponse(
result: "fault",
success: false,
data: nil,
message: "Kullanıcı adı veya şifre hatalı",
errCode: "E0000"
)
subject.send(response)
return
}
print("AuthLogin Token -------> \(token)")
ApplicationVariables.token = token
ApplicationVariables.customer = data.data?.customer
ApplicationVariables.config = data.data?.store?.config
ApplicationVariables.logo = data.data?.store?.logo
subject.send(data)
}else {
let error = NSError(domain: "Bir sorun oluştu. Lütfen yöneticinize başvurunuz.", code: 1001, userInfo: nil)
subject.send(error)
}
}
}
}
This is my code base , the problem is I couldn't find the right return , what should I return in this function or how ? I tried subject.eraseToAnyPublisher() but its not match with return type.
In line with declaring subject var subject = PassthroughSubject<Any,Error>()
change Output generic to AuthResponse
You should send errors as errors rather than values, you can send error with subject.send(completion: .failure(#Error#)).
subject.send(#Output#) sends a value
fixed code:
func reqAuth(serviceParams: AuthServiceParams) -> AnyPublisher<AuthResponse, Error> {
var subject = PassthroughSubject<AuthResponse, Error>()
AlamofireService.auth(serviceParams: serviceParams).responseObject { (response : DataResponse<AuthResponse>) in
guard response.error == nil else {
print("❌⭕️❌ Auth login hatalı bir dönüş aldı sorun var.")
subject.send(completion: .failure(response.error!))
return
}
if let data = response.result.value {
guard let token = data.data?.token else {
print("TOKEN BULUNAMADI")
let authResponse = AuthResponse(
result: "fault",
success: false,
data: nil,
message: "Kullanıcı adı veya şifre hatalı",
errCode: "E0000"
)
subject.send(response)
return
}
print("AuthLogin Token -------> \(token)")
ApplicationVariables.token = token
ApplicationVariables.customer = data.data?.customer
ApplicationVariables.config = data.data?.store?.config
ApplicationVariables.logo = data.data?.store?.logo
subject.send(data)
} else {
let error = NSError(domain: "Bir sorun oluştu. Lütfen yöneticinize başvurunuz.", code: 1001, userInfo: nil)
subject.send(completion: .failure(error))
}
}
}
New to swiftui and don't understand why the JSONDecoder() line in the first code throws
[SwiftUI] Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.
This to me is not updating ui so why is this showing?
do {
// pass the request type, bearer token, and email / password ( which are sent as POST body params )
let request = L.getRequest(requestType:"POST", token: token, email: self.username, password: self.psw)
L.fetchData(from: request) { result in
switch result {
case .success(let data):
// covert the binary data to a swift dictionary
do {
let response = try JSONDecoder().decode(WpJson.self, from: data)
for (key, title) in response.allowedReadings {
let vimeoId = Int( key )!
let vimeoUri = self.buildVimeoUri(vimeoId: key)
self.addReadingEntity(vimeoUri: vimeoUri, vimeoId: vimeoId, title: title)
}
self.writeToKeychain(jwt:response.jwt, displayName: response.displayName)
readings = self.fetchReadings()
}
catch {
self.error = error.localizedDescription
}
case .failure(let error):
self.error = error.localizedDescription
}
}
}
I tried wrapping a main queue around the do-catch in the L.fetchData(from: request) { result in but this did not help
DispatchQueue.main.async { [weak self] in
Here is the Login protocol, again without any ui work:
import Foundation
import SwiftUI
struct Login: Endpoint {
var url: URL?
init(url: URL?) {
self.url = url
}
}
protocol Endpoint {
var url: URL? { get set }
init(url: URL?)
}
extension Endpoint {
func getRequestUrl() -> URLRequest {
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object
return URLRequest(url: requestUrl)
}
func getRequest(requestType:String="POST", token:String, email:String="", password:String="") -> URLRequest {
var request = self.getRequestUrl()
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
if ( "" != email && "" != password && requestType == "POST") {
let parameters:[String:String?] = [
"email": email,
"password": password
]
// Run the request
do {
// pass dictionary to nsdata object and set it as request body
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
}
return request;
}
func fetchData(from request: URLRequest, completion: #escaping (Result<Data, NetworkError>) -> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
completion(.success(data))
} else if error != nil {
// any sort of network failure
completion(.failure(.requestFailed))
} else {
// this ought not to be possible, yet here we are
completion(.failure(.unknown))
}
}.resume()
}
}
extension URLSession {
func dataTask(with request: URLRequest, completionHandler: #escaping (Result<(Data, HTTPURLResponse), Error>) -> Void) -> URLSessionDataTask {
return dataTask(with: request, completionHandler: { (data, urlResponse, error) in
if let error = error {
completionHandler(.failure(error))
} else if let data = data, let urlResponse = urlResponse as? HTTPURLResponse {
completionHandler(.success((data, urlResponse)))
}
})
}
}
Do you have any idea on how to fix this?
Wrap it right in place of assignment
catch {
DispatchQueue.main.async {
self.error = error.localizedDescription
}
}
case .failure(let error):
DispatchQueue.main.async {
self.error = error.localizedDescription
}
}
Got these errors with this code:
if let url = URL(string: "<valid web service url string>") {
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Basic \(base64Authorization)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
if error == nil {
The same code returns no error with Xcode 7.3 but errors in Xcode 8 after converting to Swift 3.
This happened because of the Swift 3 proposal SE-0054.
base64Authorization was declared this way:
static var base64Authorization:String! {
get {
if base64Auth == nil {
let keyString = "<my key string>"
let plainTextData = keyString.data(using: .utf8, allowLossyConversion: false) as Data!
base64Auth = plainTextData!.base64EncodedString(options: .endLineWithLineFeed) as String!
}
return base64Auth
}
}
base64Authorization returned an Optional which messed up the "Basic \(base64Authorization)" HTTP setting.
This declaration of base64Authorization fixed the problem:
static var base64Authorization:String {
get {
if base64Auth == nil {
let keyString = "<my key string>"
let plainTextData = keyString.data(using: .utf8, allowLossyConversion: false) as Data!
base64Auth = plainTextData!.base64EncodedString(options: .endLineWithLineFeed) as String
}
return base64Auth!
}
}