Last active
November 7, 2017 14:30
-
-
Save randhirraj3130/2dd73aff3ff17c2887718f8ac205dd1d to your computer and use it in GitHub Desktop.
how to send data on server in ios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func sendData() | |
{ | |
let old_price = Price.text! | |
UserDefaults.standard.setValue(old_price, forKey: "old_price") | |
let prs = [ | |
"coupon_code": CoupanField.text! as String , | |
"order_price" : "\(final_price)" | |
] as [String:String] | |
Service.Start(VC: self,dic: prs, url: "\(GlobalVariable.serverName)coupon.php", onCompletion: { result in | |
print("result \(result)") | |
DispatchQueue.main.async(execute: { | |
if let myArray = result as? NSDictionary{ | |
var message = "" | |
if let msg = myArray.value(forKey: "message") as? NSString{ | |
print("messgae is:: \(msg)") | |
message = msg as String | |
} | |
if let data = myArray.value(forKey: "finalprice") as? Float{ | |
print("final price is:: \(data)") | |
self.final_price = Int(ceil(data)) | |
print("intege value is \(self.final_price)") | |
} | |
if let data = myArray.value(forKey: "percentage") as? NSString{ | |
self.discount_price = data.integerValue | |
print("percentage is:: \(self.discount_price)") | |
} | |
if let Mystatus = myArray.value(forKey: "status") as? NSString{ | |
print("status \(self.status)") | |
if(Mystatus.isEqual(to: "OK")){ | |
self.DecBtn.isUserInteractionEnabled = false | |
self.IncBtn.isUserInteractionEnabled = false | |
self.CoupanField.isUserInteractionEnabled = false | |
self.ApplyBtn.setTitle("Remove",for: .normal) | |
self.Discount.isHidden = false | |
self.ApplyBtn.tag = 1 | |
self.Discount.text = "(Discount \(self.discount_price)%)" | |
self.OriginalPrice.isHidden = false | |
self.OriginalPrice.text = "\(old_price)" | |
let title = NSAttributedString(string: "\(old_price)", attributes: [NSStrikethroughColorAttributeName:UIColor.black,NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)]) | |
self.OriginalPrice.attributedText = title | |
self.Price.text = "\(self.final_price)" | |
}else if(Mystatus.isEqual(to: "NOT OK")){ | |
let alert = UIAlertController(title: "", message: message, preferredStyle: .alert) | |
let retry = UIAlertAction(title: "Retry", style: .default, handler: { action in | |
}) | |
alert.addAction(retry) | |
self.present(alert, animated: true, completion: nil) | |
} | |
} | |
} | |
}) | |
}) | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(void)sendData:(NSString*)user_id :(NSString*)user_name :(NSString*)user_email :(NSString*)type { | |
NSString *urlString=@"http://randhir.in/hnl/sociallogin.php"; | |
NSURL *url = [NSURL URLWithString:urlString]; | |
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url]; | |
NSString *dataString = [NSString stringWithFormat:@"id=%@&email=%@&username=%@&type=%@",user_id,user_email,user_name,type]; | |
NSData *requestData = [dataString dataUsingEncoding:NSUTF8StringEncoding]; | |
NSLog(@"requestData%@",requestData); | |
[urlRequest setHTTPMethod:@"POST"]; | |
[urlRequest setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"]; | |
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; | |
[urlRequest setHTTPBody: requestData]; | |
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { | |
NSLog(@"data=%@",data); | |
if (data.length>0 && error==nil) { | |
@try { | |
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; | |
// NSString *dict = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; | |
NSLog(@"Dict=%@",dict); | |
NSString *ss = [NSString stringWithFormat:@"%@",[dict valueForKey:@"result"]]; | |
NSLog(@"ss %@",ss); | |
if([ss isEqualToString:@"success"]){ | |
NSDictionary*user_data = [dict valueForKey:@"data"]; | |
NSString *user_id = [NSString stringWithFormat:@"%@",[user_data valueForKey:@"id"]]; | |
NSString *user_email = [NSString stringWithFormat:@"%@",[user_data valueForKey:@"email"]]; | |
NSString *user_image_url = [NSString stringWithFormat:@"%@",[user_data valueForKey:@"profile_pic"]]; | |
NSString *user_name = [NSString stringWithFormat:@"%@",[user_data valueForKey:@"username"]]; | |
// set the value in prefrences | |
[[NSUserDefaults standardUserDefaults]setValue:user_id forKey:@"user_id"]; | |
[[NSUserDefaults standardUserDefaults]setValue:user_email forKey:@"email"]; | |
[[NSUserDefaults standardUserDefaults]setValue:user_image_url forKey:@"image_url"]; | |
[[NSUserDefaults standardUserDefaults]setValue:user_name forKey:@"user_name"]; | |
[[NSUserDefaults standardUserDefaults ]setValue:@"social_login" forKey:@"social_login"]; | |
NSLog(@"user details %@ %@ %@ %@ ", user_name ,user_id ,user_email,user_image_url); | |
NSLog(@"success"); | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
// [[self processView]setHidden:true]; | |
// [[self processView]setHidden:YES]; | |
[[self processHolderView]setHidden:YES]; | |
//[[NSUserDefaults standardUserDefaults]setValue:@"name" forKey:@"name"]; | |
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; | |
UITabBarController*vc = [storyboard instantiateViewControllerWithIdentifier: @"MyTabBarController"]; | |
self.navigationItem.hidesBackButton = YES; | |
self.navigationItem.backBarButtonItem = nil; | |
[[self navigationController]pushViewController:vc animated:YES]; | |
}); | |
}else{ | |
[[self processHolderView]setHidden:true]; | |
UIAlertController * alert = [UIAlertController | |
alertControllerWithTitle:@"Invalid" | |
message:@"Invalid email or passwor.try Again!" | |
preferredStyle:UIAlertControllerStyleAlert]; | |
UIAlertAction* fbButton = [UIAlertAction | |
actionWithTitle:@"Retry" | |
style:UIAlertActionStyleDefault | |
handler:^(UIAlertAction * action) | |
{ | |
[[self processHolderView]setHidden:true]; | |
// [[self processView]setHidden:YES]; | |
[[self loginBtn]setUserInteractionEnabled:YES]; | |
// Add your code | |
}]; | |
[alert addAction:fbButton]; | |
[self presentViewController:alert animated:YES completion:nil]; | |
} | |
} @catch (NSException *exception) { | |
NSLog(@"Exception %@",exception.description); | |
} @finally { | |
} | |
} | |
}]; | |
[dataTask resume]; | |
NSLog(@"getData true working"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// WebService.swift | |
// ArtCaller | |
// | |
// Created by Twistfuture on 6/9/15. | |
// Copyright (c) 2015 Twist. All rights reserved. | |
// | |
import Foundation | |
import UIKit | |
@objc protocol WebServiceDelegate { | |
@objc optional func CompleteDownloading ( _ service :WebService ,result : AnyObject) | |
} | |
class WebService : NSObject { | |
var delegate : WebServiceDelegate? | |
var View : UIView = UIView() | |
var Process : UIActivityIndicatorView = UIActivityIndicatorView() | |
var task : URLSessionDataTask! | |
func Start(VC: UIViewController, dic : [String:String]?,url : String, onCompletion : @escaping (AnyObject) -> Void) { | |
// print(dic) | |
let win:UIWindow = UIApplication.shared.delegate!.window!! | |
let urlString = "\(url)" | |
print(urlString) | |
let url = Foundation.URL(string : urlString ) | |
let request = NSMutableURLRequest(url : url!) | |
request.httpMethod="POST" | |
let boundary = NSString(format: "---------------------------147378355409831466499882746641449") | |
let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary) | |
request.addValue(contentType as String, forHTTPHeaderField: "Content-Type") | |
let body = NSMutableData() | |
self.View.frame = CGRect(x: 0, y: 0, width: 50, height: 50) | |
self.View.backgroundColor = UIColor.gray | |
self.View.center = win.center | |
self.View.layer.cornerRadius = 5.0 | |
self.View.clipsToBounds = true | |
self.Process.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white | |
self.Process.center = CGPoint(x: 25, y: 25) | |
self.View.addSubview(self.Process) | |
self.Process.startAnimating() | |
VC.view.addSubview(self.View) | |
if dic != nil { | |
print(dic!) | |
for (key, text) in dic! { | |
print("Sending ----\(key)-----\(text)") | |
body.append(NSString(format: "\r\n--%@\r\n",boundary).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(NSString(format:"Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(text.data(using: String.Encoding.utf8, allowLossyConversion: true)!) | |
} | |
} | |
request.httpBody = body as Data | |
task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { | |
data, response, error in | |
DispatchQueue.main.async(execute: { | |
self.View.removeFromSuperview() | |
if error != nil | |
{ | |
let alert = UIAlertController(title: "Error", message: "Server is not responding properly.", preferredStyle: .alert) | |
let cancel = UIAlertAction(title: "Retry", style: .cancel, handler: { action in | |
self.task.resume() | |
}) | |
alert.addAction(cancel) | |
VC.present(alert, animated: true, completion: nil) | |
}else{ | |
let srt = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) | |
print("Service : \(url) Data: \(srt)") | |
do { | |
let parsedObject = try JSONSerialization.jsonObject(with: data!, options: []) | |
if let object = parsedObject as? NSDictionary{ | |
print("Result is a dictionary"); | |
onCompletion(object) | |
}else{ | |
print("Result is an array"); | |
} | |
} catch { | |
print("json error: \(error)") | |
} | |
} }) | |
}) | |
if(Controller.isConnectedToNetwork()){ | |
print("internet connectivity found ") | |
task.resume() | |
}else{ | |
self.View.removeFromSuperview() | |
print("internet connectivity not found ") | |
let alert = UIAlertController(title: "Error", message: "internet connectivity not found", preferredStyle: .alert) | |
let cancel = UIAlertAction(title: "Retry", style: .cancel, handler: { action in | |
self.task.resume() | |
}) | |
alert.addAction(cancel) | |
VC.present(alert, animated: true, completion: nil) | |
} | |
} | |
func StartFacebook(VC: UIViewController, dic : [String:String]?,url : String, onCompletion : @escaping (AnyObject) -> Void) { | |
// print(dic) | |
let win:UIWindow = UIApplication.shared.delegate!.window!! | |
let urlString = "\(url)" | |
print(urlString) | |
let url = Foundation.URL(string : urlString ) | |
let request = NSMutableURLRequest(url : url!) | |
request.httpMethod="GET" | |
let boundary = NSString(format: "---------------------------147378355409831466499882746641449") | |
let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary) | |
request.addValue(contentType as String, forHTTPHeaderField: "Content-Type") | |
let body = NSMutableData() | |
View.frame = CGRect(x: 0, y: 0, width: 50, height: 50) | |
View.backgroundColor = UIColor.gray | |
View.center = win.center | |
View.layer.cornerRadius = 5.0 | |
View.clipsToBounds = true | |
Process.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white | |
Process.center = CGPoint(x: 25, y: 25) | |
View.addSubview(Process) | |
Process.startAnimating() | |
VC.view.addSubview(View) | |
if dic != nil { | |
print(dic!) | |
for (key, text) in dic! { | |
print("Sending ----\(key)-----\(text)") | |
body.append(NSString(format: "\r\n--%@\r\n",boundary).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(NSString(format:"Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(text.data(using: String.Encoding.utf8, allowLossyConversion: true)!) | |
} | |
} | |
request.httpBody = body as Data | |
task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { | |
data, response, error in | |
DispatchQueue.main.async(execute: { | |
self.View.removeFromSuperview() | |
if error != nil | |
{ | |
let alert = UIAlertController(title: "Error", message: "internet connectivity not found", preferredStyle: .alert) | |
let cancel = UIAlertAction(title: "Retry", style: .cancel, handler: { action in | |
self.task.resume() | |
}) | |
alert.addAction(cancel) | |
VC.present(alert, animated: true, completion: {}) | |
print(error.debugDescription) | |
}else{ | |
let srt = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) | |
print("Service : \(url) Data: \(srt)") | |
do { | |
let parsedObject = try JSONSerialization.jsonObject(with: data!, options: []) | |
if let object = parsedObject as? NSDictionary{ | |
print("Result is a dictionary"); | |
onCompletion(object) | |
}else{ | |
print("Result is an array"); | |
} | |
} catch { | |
print("json error: \(error)") | |
} | |
} }) | |
}) | |
if(Controller.isConnectedToNetwork()){ | |
print("internet connectivity found ") | |
task.resume() | |
}else{ | |
self.View.removeFromSuperview() | |
print("internet connectivity not found ") | |
let alert = UIAlertController(title: "Error", message: "internet connectivity not found", preferredStyle: .alert) | |
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: { action in | |
self.task.resume() | |
}) | |
alert.addAction(cancel) | |
VC.present(alert, animated: true, completion: {}) | |
} | |
} | |
func StartWithData(VC: UIViewController, dic : [String:AnyObject]?,url : String, onCompletion : @escaping (AnyObject) -> Void) { | |
// print(dic) | |
let win:UIWindow = UIApplication.shared.delegate!.window!! | |
let urlString = "\(url)" | |
// print(urlString) | |
let url = Foundation.URL(string : urlString ) | |
let request = NSMutableURLRequest(url : url!) | |
request.httpMethod="POST" | |
let boundary = NSString(format: "---------------------------147378355409831466499882746641449") | |
let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary) | |
request.addValue(contentType as String, forHTTPHeaderField: "Content-Type") | |
let body = NSMutableData() | |
View.frame = CGRect(x: 0, y: 0, width: 50, height: 50) | |
View.backgroundColor = UIColor.gray | |
View.center = win.center | |
View.layer.cornerRadius = 5.0 | |
View.clipsToBounds = true | |
Process.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white | |
Process.center = CGPoint(x: 25, y: 25) | |
View.addSubview(Process) | |
Process.startAnimating() | |
VC.view.addSubview(View) | |
if dic != nil { | |
for (key, text) in dic! { | |
if let s = text as? String{ | |
//print("Sending ----\(key)-----\(text)") | |
body.append(NSString(format: "\r\n--%@\r\n",boundary).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(NSString(format:"Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(s.data(using: String.Encoding.utf8, allowLossyConversion: true)!) | |
} | |
else{ | |
if let image = text as? Data { | |
print("\(key)") | |
body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(NSString(format:"Content-Disposition: form-data; name=\"file\"; filename=\"\(key)\"\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!) | |
//let pathExtention = key.pathExtension | |
let url = Foundation.URL(fileURLWithPath: key) | |
let pathExtension = url.pathExtension | |
var sd = "" | |
if (pathExtension == "png"){ | |
sd = "image/png"; | |
}else{ | |
sd = "image/jpg"; | |
} | |
print(sd) | |
body.append(NSString(format: "Content-Type: \(sd)\r\n\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!) | |
body.append(image) | |
body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!) | |
} | |
} | |
} | |
} | |
request.httpBody = body as Data | |
task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { | |
data, response, error in | |
DispatchQueue.main.async(execute: { | |
self.View.removeFromSuperview() | |
if error != nil | |
{ | |
onCompletion("Error" as AnyObject) | |
print(error.debugDescription) | |
}else{ | |
let srt = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) | |
print("Service : \(url) Data: \(srt)") | |
do { | |
let parsedObject = try JSONSerialization.jsonObject(with: data!, options: []) | |
if let object = parsedObject as? NSDictionary{ | |
print("Result is a dictionary"); | |
onCompletion(object) | |
}else{ | |
print("Result is an array"); | |
} | |
} catch { | |
print("json error: \(error)") | |
} | |
} }) | |
}) | |
if(Controller.isConnectedToNetwork()){ | |
print("internet connectivity found ") | |
task.resume() | |
}else{ | |
self.View.removeFromSuperview() | |
print("internet connectivity not found ") | |
let alert = UIAlertController(title: "Error", message: "internet connectivity not found. please connect to internet !", preferredStyle: .alert) | |
let cancel = UIAlertAction(title: "Retry", style: .default, handler: { action in | |
//self.task.resume() | |
self.task.resume() | |
self.View.addSubview(self.Process) | |
self.Process.startAnimating() | |
VC.view.addSubview(self.View) | |
}) | |
let cancel1 = UIAlertAction(title: "Cancel", style: .cancel, handler: { action in | |
}) | |
alert.addAction(cancel) | |
alert.addAction(cancel1) | |
VC.present(alert, animated: true, completion: {}) | |
} | |
} | |
override init() { | |
} | |
} | |
class MyImageCache { | |
static let sharedCache: NSCache = { () -> NSCache<AnyObject, AnyObject> in | |
let cache = NSCache<AnyObject, AnyObject>() | |
cache.name = "weebook" | |
cache.countLimit = 200 | |
cache.totalCostLimit = 100*1024*1024 // Max 100MB used. | |
return cache | |
}() | |
} | |
extension Foundation.URL { | |
typealias ImageCacheCompletion = (UIImage) -> Void | |
var cachedImage: UIImage? { | |
return MyImageCache.sharedCache.object( | |
forKey: absoluteString as AnyObject) as? UIImage | |
} | |
func fetchImage(_ completion: @escaping ImageCacheCompletion) { | |
let task = URLSession.shared.dataTask(with: self, completionHandler: { | |
data, response, error in | |
if error == nil { | |
if let data = data, | |
let image = UIImage(data: data) { | |
MyImageCache.sharedCache.setObject( | |
image, | |
forKey: self.absoluteString as AnyObject, | |
cost: data.count) | |
DispatchQueue.main.async { | |
completion(image) | |
} | |
} | |
} | |
}) | |
task.resume() | |
} | |
} | |
var Service : WebService = WebService() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment