How to share text and images on whatsapp , linkedln and Facbook in ios swift? - swift

i am using this url for whatsapp "whatsapp://send?text= i am able to share text but not sure how to share image same issue i am facing with linkedln "linkedin://share?text=" please let me know how can i fix it?
For FB i am using FBSDKShareKit this is my code:
func shareFBPost(){
let text = fbDescription
let content = ShareLinkContent()
content.contentURL = URL(string:fbURL)!
content.quote = text
let dialog = ShareDialog(viewController: self.vc, content: content, delegate:nil)
dialog.show()}
on using SharePhotoContent i am not able to prepopulate the text as caption is immutable
whatsapp i am using this :
fileprivate func referWhatsapp(description:String){
print("referral message:\(description)")
let urlWhats = "whatsapp://send?text=\(description)"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL) {
UIApplication.shared.open(whatsappURL, options: [:], completionHandler: nil)
} else {
let alert = UIAlertController(title: "Error!", message: "Sorry, WhatsApp app is not found on device. Please select another mode.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
self.vc?.dismiss(animated: true, completion: nil)
}))
self.vc?.present(alert, animated: true, completion: nil)
}
}
}
}
linkedln:
if linkedLNDescription != ""{
let message = linkedLNDescription
let encodedMessage =
message.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let urlString = "linkedin://share?text=\(encodedMessage)"
let url = URL(string: urlString)!
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler:
nil) }
please let me know how can we share both text and image on social media platform

Related

How to get real database of resized image?

I am using firebase resized image extension to resize my image to get different thumbs.The images get resized correctly. Anyway, I wrote this code to insert the original image in real database.
func sendDataToFirebase(){
let productID = self.ref.childByAutoId().key
let product = [
"imagesID" : productID,
"originalImage" : self.imgURL as String
]
self.ref.child("images").child(productID!).setValue(product)
let alertController = UIAlertController(title: "Alert", message: "The image has been saved", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
And this to store the image
func storeImageInFirebase(){
let storeageRef = Storage.storage().reference()
let imageName = UUID().uuidString + ".jpg"
let imagesReference = storeageRef.child("images").child(imageName)
let imageData = self.imgView.image!.pngData()
let metaData = StorageMetadata()
metaData.contentType = "image/jpg"
imagesReference.putData(imageData!, metadata: metaData){ (metadate, error)
in
guard metadate != nil else{
print("Error: \(String(describing: error?.localizedDescription))")
return
}
imagesReference.downloadURL(completion: {(url, error)
in
if error != nil {
print("Faild to download url:", error!)
return
}else{
// do something with url
self.imgURL = (url?.absoluteString)!
self.sendDataToFirebase()
//print(self.imgURL)
}
})
}
}
This is according to original image. What I want is to know how can get and sent the resized image to real database?

App freezes after popping a view

I have the main window where I just load a collection view like this
let urlString = "http://example.url"
let url = NSURL(string: urlString)!
let urlSession = URLSession.shared
let jsonQuery = urlSession.dataTask(with: url as URL, completionHandler: {
data, response, error -> Void in
if (error != nil) {
print("ERROR \(error!.localizedDescription)")
}else{
let jsonResult = (try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary
let arrayImagenes1 = jsonResult["franjas"]! as! NSMutableArray
arrayImagenes1.removeObject(at: 0)
arrayImagenes1.removeObject(at: 0)
self.arrayImagenes = arrayImagenes1 as NSArray
print (self.arrayImagenes)
self.franjasCollection.reloadData()
}
})
jsonQuery.resume()
And in that view I call a login window where I just login to the app like this
let urlString = "http://example.login"
let url = NSURL(string: urlString)!
let urlSession = URLSession.shared
let jsonQuery = urlSession.dataTask(with: url as URL, completionHandler: {
data, response, error -> Void in
if (error != nil) {
print("ERROR \(error!.localizedDescription)")
}else{
let jsonResult = (try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary
if jsonResult["username"] != nil {
let usuario = jsonResult["username"]! as? NSString
DispatchQueue.main.async {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let username = Usuario(context: context) // Link Task & Context
username.username = usuario! as String
}
(UIApplication.shared.delegate as! AppDelegate).saveContext()
Variables.loginbool = true
let _ = self.navigationController?.popViewController(animated: true)
} else {
let alert = UIAlertController(title: "Inti", message: (jsonResult["error"]! as! NSString) as String, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
jsonQuery.resume()
So, after the user succesfully login in the app, I use this line
let _ = self.navigationController?.popViewController(animated: true)
But when it comes back to the Main View the collection view is frozen and I can not navigate in it, I can only click the login button
PD: it is an apple tv app

How to store value and retrive it to use in next view controller after login using userdefaults?

I want to store the ngoid value in userDefaults so that I can access it in my next API call in the next viewController class. How do I do it?
Here is the code I have written:
#IBAction func loginbutton(_ sender: Any) {
let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")
let request = NSMutableURLRequest(url:myUrl! as URL)
request.httpMethod = "POST"// Compose a query string
let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in
if error != nil
{
//let alert = UIAlertView()
let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
return
}
// You can print out response object
print("*****response = \(String(describing: response))")
let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )
if ((responseString?.contains("")) == nil) {
print("incorrect - try again")
let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in
}
// Add Actions
alert.addAction(yesAction)
// Present Alert Controller
self.present(alert, animated: true, completion: nil)
}
else {
print("correct good")
}
print("*****response data = \(responseString!)")
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
if let email = json["UserName"] as? String,
let password1 = json["passowrd"] as? String {
print ("Found User id: called \(email)")
}
let msg = (json.value(forKey: "message") as! NSString!) as String
//let id = json.value(forKey: "NgoId") as! Int!
let ngoid = json.value(forKey: "NgoId") as? String
print(ngoid ?? "")
let defaults = UserDefaults.standard
defaults.set(ngoid, forKey: "ngoid")
print(ngoid!)
DispatchQueue.main.async {
self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
let vtabbar1 = self.storyboard?.instantiateViewController(withIdentifier: "tabbar1")
self.navigationController?.pushViewController(vtabbar1!, animated: true)
}
self.alert.addAction(self.action)
self.present(self.alert, animated: true, completion: nil)
}
}
}
catch let error {
print(error)
}
}
task.resume()
}
You could use UserDefaults but if you only need to use the value on the next viewController you should use a segue for this purpose. Here is a guide of how that works. Otherwise use UserDefaults like the example below:
// To set the value
UserDefaults.standard.set(ngoid, forKey: "NgoId")
// To get the value
let id = UserDefaults.standard.string(forKey: "NgoId")
This is not a best way to save in user default and then use in next ViewController, use this overdid method
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowCounterSegue"
{
if let destinationVC = segue.destinationViewController as? OtherViewController {
destinationVC.ngoid = ngoid
}
}
}
use ngoid anywhere in your next ViewController api call.

iOS swift 3.0 Json parsing and alert issue

I'm working on login form. I'm a fresher on iOS development.
After successful login, I want to show an alert after completion of json parsing. I've parsed Ngoid inside a do while block. Now I want to pass the value "Ngoid" to the next view controller so that it can be used to fetch the further data.
Main Problem: Here is the code I have written and it gives me error to write alert it on main thread only.
As I want the "Ngoid" value for further use there, so how should I write it and what is the correct way to execute the code?
Here is the code I have written:
#IBAction func loginbutton(_ sender: Any) {
let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")
let request = NSMutableURLRequest(url:myUrl! as URL)
request.httpMethod = "POST"// Compose a query string
let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in
if error != nil
{
//let alert = UIAlertView()
let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
return
}
// You can print out response object
print("*****response = \(String(describing: response))")
let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )
if ((responseString?.contains("")) == nil) {
print("incorrect - try again")
let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in
}
// Add Actions
alert.addAction(yesAction)
// Present Alert Controller
self.present(alert, animated: true, completion: nil)
}
else {
print("correct good")
}
print("*****response data = \(responseString!)")
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
if let email = json["UserName"] as? String,
let password1 = json["passowrd"] as? String {
print ("Found User id: called \(email)")
}
let msg = (json.value(forKey: "message") as! NSString!) as String
let id = (json.value(forKey: "NgoId") as! NSString!) as String
// let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
// alert.show()
self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
print("the alert\(self.alert)")
self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
let viewControllerYouWantToPresent = self.storyboard?.instantiateViewController(withIdentifier: "pass1") as! ViewControllerngodetails
viewControllerYouWantToPresent.temp1 = self.id
self.present(viewControllerYouWantToPresent, animated: true, completion: nil)
}
self.alert.addAction(self.action)
self.present(self.alert, animated: true, completion: nil)
}
}catch let error {
print(error)
}
}
task.resume()
}
A pro tip:
All your UI related tasks need to be done in the main thread. Here you are presenting the alert inside a closure which executes in a background thread, thats the problem. You need to call the main queue and present alert in that block.
EDIT:
Just put your alert code in this-
For Swift 3-
Get main queue asynchronously
DispatchQueue.main.async {
//Code Here
}
Get main queue synchronously
DispatchQueue.main.sync {
//Code Here
}
Every UI update has to be on main thread:
#IBAction func loginbutton(_ sender: Any) {
let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")
let request = NSMutableURLRequest(url:myUrl! as URL)
request.httpMethod = "POST"// Compose a query string
let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in
if error != nil
{
DispatchQueue.main.async {
let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
// Present Alert Controller
self.present(alert, animated: true, completion: nil)
}
return
}
// You can print out response object
print("*****response = \(String(describing: response))")
let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )
if ((responseString?.contains("")) == nil) {
print("incorrect - try again")
DispatchQueue.main.async {
let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in }
// Add Actions
alert.addAction(yesAction)
// Present Alert Controller
self.present(alert, animated: true, completion: nil)
}
}
else {
print("correct good")
}
print("*****response data = \(responseString!)"
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
if let email = json["UserName"] as? String,
let password1 = json["passowrd"] as? String {
print ("Found User id: called \(email)")
}
let msg = (json.value(forKey: "message") as! NSString!) as String
let id = (json.value(forKey: "NgoId") as! NSString!) as String
DispatchQueue.main.async {
self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
print("the alert\(self.alert)")
self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
let viewControllerYouWantToPresent = self.storyboard?.instantiateViewController(withIdentifier: "pass1") as! ViewControllerngodetails
viewControllerYouWantToPresent.temp1 = self.id
self.present(viewControllerYouWantToPresent, animated: true, completion: nil)
}
self.alert.addAction(self.action)
self.present(self.alert, animated: true, completion: nil)
}
}
}catch let error {
print(error)
}
}
task.resume()
}

rare issue with a Video downloaded and played in iPad or iPhone

I developed an application and one of the functionalities is to see a video that I downloaded from a server. I'm using Alamofire to access the network, this is my code:
func GetVideoFiedMedia(videoFiedData: VideofiedVideo?, completionHandler: (NSURL?, NSError?) -> ()) {
var result: NSURL? = nil;
let parameters : [ String : AnyObject] = [
"CnxID": (videoFiedData?.cnxID!)!,
"TaskNum": (videoFiedData?.taskNum!)!,
"Ev_File": (videoFiedData?.evFile!)!
]
let headers = [
"Content-Type": "application/json"
]
let urlAux = "https://xxxxxx/xxxxx/xxxxx.svc/VideoMedia?";
Alamofire.request(.POST, urlAux, parameters: parameters, headers: headers, encoding: .JSON)
.validate()
.responseString { response in
switch response.result {
case .Success:
if let JSON = response.result.value {
do{
let data: NSData = JSON.dataUsingEncoding(NSUTF8StringEncoding)!
let decodedJson = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! NSDictionary
let dObj = decodedJson["d"] as! NSDictionary;
let resultSet = dObj["Media"] as? NSArray;
if(resultSet != nil){
let stringsData = NSMutableData();
for item in resultSet! {
let byte = item as! Int;
var char = UnicodeScalar(byte);
stringsData.appendBytes(&char, length: 1)
}
var destinationUrl: NSURL? = nil;
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL;
let fileName = "msavid.mp4";
destinationUrl = documentsUrl.URLByAppendingPathComponent(fileName)
let fileMangr = NSFileManager.defaultManager()
var fileHandle = NSFileHandle.init(forWritingAtPath: (destinationUrl?.path!)!)
if(fileHandle == nil){
fileMangr.createFileAtPath((destinationUrl?.path!)!, contents: stringsData, attributes: nil)
fileHandle = NSFileHandle.init(forWritingAtPath: (destinationUrl?.path!)!)
}
if(fileHandle != nil){
fileHandle?.seekToEndOfFile();
fileHandle?.writeData(stringsData);
fileHandle?.closeFile();
}
result = destinationUrl;
completionHandler(result, nil);
}
}catch{
result = nil;
completionHandler(result, nil);
}
}
case .Failure(let error):
completionHandler(result, error);
}
}
}
When I got the nsurl for the video I played it in this way:
_ = self.manager.GetVideoFiedMedia(videoFiedItem, completionHandler: { responseObject, error in
if(responseObject != nil){
var sendSegue = false;
self.nsurl = responseObject;
if NSFileManager().fileExistsAtPath(responseObject!.path!) == true {
if(sendSegue == false){
self.performSegueWithIdentifier("sureViewSegue", sender: nil);
self.nsurl = nil;
sendSegue = true;
MBProgressHUD.hideAllHUDsForView(self.view, animated: true);
}
}else{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
let alert = UIAlertController(title: "Alert", message: "We have problem to download the media data, please try again later.", preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
}else{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
let alert = UIAlertController(title: "Alert", message: "We have problem to download the media data, please try again later.", preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
})
The segue that I performed push a AVPlayerViewController.
When I was testing the method using the iOS simulator everything seems to work fine, the problem came when I tried to use the functionality in a real device(iPhone or iPad)the video doesn't show up, I got the AVPlayerViewController with this symbol that can't reproduce the video.
Please any help on this, I can't figure out what is causing the problem.
So simple and at the same time unthinkable, just reset the device and erase the copy of the file msavid.mp4 in the phone and it is working.