Profile Image does not appear when I run the app. - swift3

Theres no error in my code but ImagevIew image doesn't show
let imageCache = NSCache()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString: String) {
//self.image = nil
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async(execute: {
if let currImage = UIImage(data: data!) {
imageCache.setObject(currImage, forKey: urlString as AnyObject)
self.image = currImage
}
})
}).resume()
}
}

Related

I Found Error of Could Not Cast Value of Type when i load my json in Tableview

This is my code , could not append array type to UIImage , api is successfully loaded , i have problem in appending data
var images = UIImage
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSObject {
print(jsonObj!.value(forKey: "guid"))
if let actorArray = jsonObj!.value(forKey: "guid") as? [NSObject] {
if let actorDict = actorArray as? NSObject
{
if let name = actorDict.value(forKey: "rendered") {
**self.images.append(name as! UIImage)**
print("\(name)")
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
this is my rest api
guid {1}
rendered : http://thenewschef.com/wp-content/uploads/2018/02/startup.jpeg
So, You Can Do This
var images = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
downloadJsonWithURL()
}
//Tableview methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 135
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DemoTableCell", for: indexPath) as! DemoTableCell
let dict = images[indexPath.row]
URLSession.shared.dataTask(with: NSURL(string: dict["rendered"] as! String)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error as Any)
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
cell.imgView?.image = image
})
}).resume()
return cell
}
//your api call
func downloadJsonWithURL() {
let urlString = "https://thenewschef.com/wp-json/wp/v2/media"
let url = NSURL(string: urlString)
print(url as Any)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) {
print((jsonObj as AnyObject).value(forKey: "guid") as Any)
let responseJSON = (jsonObj as AnyObject).value(forKey: "guid") as Any
let json = (responseJSON as AnyObject) as? NSArray
self.images = json as! [[String:AnyObject]]
print(self.images)
OperationQueue.main.addOperation({
self.demoTable.reloadData()
})
}
}).resume()
}
That's it you got your UIImage.
Enhanced implementation of above solution using Higher order function to avoid all the cast dance.
Use the below code to fetch the response form Server & filter the required imageUrl's in a single array.
func downloadJsonWithURL() {
let urlString = "https://thenewschef.com/wp-json/wp/v2/media"
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {[weak self] (data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) {
let guids = (jsonObj as? [[String: Any]])?.map { $0["guid"] }
let imagesArray = (guids as? [[String: Any]])?.map {$0["rendered"]} as? [String]
OperationQueue.main.addOperation({
//Reload Table here...
})
}
}).resume()
}

Sharing photo with Whatsapp not working under Xcode 9.1 and iOS11

The below code used to work in Xcode8. But now it is not working in Xcode 9.1 with target iOS11.
I did the following:
class ViewController: UIViewController {
var documentInteractionController: UIDocumentInteractionController = UIDocumentInteractionController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func ShareImages(_ sender: AnyObject)
{
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
if let image = UIImage(named: "whatsappIcon") {
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.write(to: tempFile, options: .atomic)
self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
self.documentInteractionController.uti = "net.whatsapp.image"
self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
} catch {
print(error)
}
}
}
} else {
// Cannot open whatsapp
}
}
}
}
// Added this in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>

Swift3 Play multiple video files with AVPlayer

I have a little code which allows me to play a local file when I hit a UIButton. But what I want is to play multiple files on 3 different UIButtons because I have 3 video files which I want to attach to my app.
This is the current code:
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
var playerController = AVPlayerViewController()
var player:AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let videoString:String? = Bundle.main.path(forResource: "Video", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func PlayVideo(_ sender: AnyObject) {
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
}
You can create url for different video file in your button click funtions
#IBAction func Button1Click(_ sender: AnyObject) {
let videoString:String? = Bundle.main.path(forResource: "Video1", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
#IBAction func Button2Click(_ sender: AnyObject) {
let videoString:String? = Bundle.main.path(forResource: "Video2", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
#IBAction func Button3Click(_ sender: AnyObject) {
let videoString:String? = Bundle.main.path(forResource: "Video3", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}

Updating an URLSession to swift 3 throwing error

I updated my code to Swift 3 and most of it converted over fine except from the URLSession and I cant find a solution to this error:
Cannot invoke 'dataTask' with an argument list of type '(with: NSMutableURLRequest, completionHandler: (Data?, URLResponse?, NSError?) -> Void)'
This is my code:
let post:NSString = "username=\(username)&userPassword=\(password)&userEmail=\(email)" as NSString
let url:URL = URL(string: "http://ec2-54-201-55-114.us-west-2.compute.amazonaws.com/wickizerApp/ApplicationDB/scripts/registerUser.php")!
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = post.data(using: String.Encoding.utf8.rawValue)
URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:NSError?) -> Void in
DispatchQueue.main.async
{
if error != nil {
self.displayAlertMessage(error!.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let status = parseJSON["status"] as? String
if( status! == "200")
{
let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){(action) in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
} else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
self.displayAlertMessage(errorMessage!)
}
}
}
} catch{
print(error)
}
}
}).resume()
Is there a different way to do requests in swift 3 or did they just change the way to do them?
The compiler wants URLRequest and Error
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = post.data(using: .utf8)
URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in
})
or still shorter
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
})
or still shorter
URLSession.shared.dataTask(with: request) { (data, response, error) in
}

I can call so imagePicker that the program is waiting for image selection

my delegate always returns nil for my image in custom table cell.
PhotoTakingHelper just class for imagepicker setting.
How i can pausing programm for pick image?
Method in CustomCell class:
#IBAction func loadImageButtonTapped(_ sender: UIButton) {
loadingImage=true
if delegate != nil {
let (image,name) = delegate.loadImageForQuestionAction(question: question)
print("Delegate return \(image)")
imageInCreatingCell = image
nameInCreatingCell = name
//loadImageButton.isHidden = true
}
}
Method in tableView class:
func loadImageForQuestionAction(question: Question) -> (UIImage?,String?) {
var returnImage:UIImage?
var returnName:String?
self.photoTakingHelper=PhotoTakingHelper(viewcontroller: self, callback: { (image:UIImage?,name:String?) in
if let photoImage = image {
print(photoImage)
print(name)
returnImage=photoImage
returnName=name
//NEED SHOWING IMAGE NAME HOW LABEL
print("loadImageAction")
}
})
return (returnImage,returnName)
}
Method in PhotoTakingHelper:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//viewController.dismiss(animated: false, completion: nil)
categoryViewController.dismiss(animated: false, completion: nil)
var fileName:String? = nil
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
fileName = result.firstObject?.value(forKey: "filename") as! String?
}
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
callBack(image,fileName)
} else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
callBack(image,fileName)
} else {
print("Something went wrong")
callBack(nil,nil)
}
}
UPDATE:
func loadImageForQuestionAction(question: Question, completion: #escaping (UIImage?, String?) -> ()) {
var returnImage:UIImage?
var returnName:String?
self.photoTakingHelper=PhotoTakingHelper(viewcontroller: self, callback: { (image:UIImage?,name:String?) in
DispatchQueue.main.async {
if let photoImage = image {
print(photoImage)
print(name)
returnImage=photoImage
returnName=name
completion(returnImage,returnName)
//NEED SHOWING IMAGE NAME HOW LABEL
print("loadImageAction")
} else {
completion(returnImage,returnName)
}
}
})
}