I am beginner so please take in advance. I am trying to show some gifs up on eby one i got in the assets folder, so i do not know how to display and put time through in those pics, because i have already got the way to show the wkwebview but i cannot get gif into WKwebView one by one with intervals among them.
Here is the code:
import UIKit
import WebKit
class SecondWebKitView: UIViewController {
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var greyView: UIView!
#IBOutlet weak var webKitView: WKWebView!
let totalCount = 13
var count = 1
var myTimer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
greyView.layer.cornerRadius = 10
let url = Bundle.main.url(forResource: "1.JumpingJacks", withExtension: "gif")!
let data = try! Data(contentsOf: url)
webKitView.load(data, mimeType: "image/gif", characterEncodingName: "UTF-8", baseURL: NSURL() as URL)
webKitView.scalesLargeContentImage = true
webKitView.contentMode = UIView.ContentMode.scaleAspectFit
let jsonUrlString = "https://fitness-db.p.rapidapi.com/7-minute-workout"
guard let url = URL(string: jsonUrlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
do {
let websiteDescription = try JSONDecoder().decode(SecondWebKitModel.self, from: data)
print(websiteDescription.description ?? "", websiteDescription.description ?? "", websiteDescription.title ?? "")
//let courses = try JSONDecoder().decode([Course].self, from: data)
DispatchQueue.main.async {
self.descriptionLabel.text = websiteDescription.description
}
} catch let jsonErr {
print("Error serializing json", jsonErr)
}
}.resume()
}
#IBAction func start(sender: AnyObject) {
myTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector(("myPerformeCode:")), userInfo: nil, repeats: true)
}
func myPerformeCode(timer : Timer) {
print("Displayed")
count += 1
if count < totalCount {
let filePath = Bundle.main.path(forResource: "\(count)", ofType: "gif")
let gif = NSData(contentsOfFile: filePath!)
self.webKitView.load(gif! as Data, mimeType: "image/gif",characterEncodingName: String(), baseURL: NSURL() as URL)
self.webKitView.isUserInteractionEnabled = false
} else {
count = 1
}
}
}
Need to solve how to show gifs up with timing. Thanks
Related
i created share extension for my app which can share image/videos from photos(Gallery) and it work properly but here problem is if i select .HEIC type file then click on my share extension it show error as shown in below screenshot .
import UIKit
import Social
import MobileCoreServices
import AVKit
import Toast_Swift
//#objc(ShareExtensionViewController)
class ShareViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
#IBOutlet weak var btn: UIButton!
#IBOutlet weak var lbl: UILabel!
#IBOutlet weak var view2: UIView!
#IBOutlet weak var cancel: UIButton!
#IBOutlet weak var blurview: UIVisualEffectView!
var allMedia = [Data()]
var singleImage = UIImage()
var imagesUrl = [URL]()
let groupPath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "
my group identifire ")
var saveDone = Bool()
override func viewDidLoad() {
super.viewDidLoad()
let attachments = (self.extensionContext?.inputItems.first as? NSExtensionItem)?.attachments ?? []
self.btn.setTitle("Add", for: .normal)
self.btn.layer.cornerRadius = 10
self.cancel.layer.cornerRadius = 10
self.image.clipsToBounds = false
applyshadow(image: image)
blurview.isHidden = true
}
override func viewDidAppear(_ animated: Bool) {
self.handleSharedFile()
}
// MARK:- function
func applyshadow(image: UIImageView) {
image.clipsToBounds = false
image.layer.shadowColor = UIColor.systemGray.cgColor
image.layer.shadowOpacity = 1
image.layer.shadowOffset = CGSize.zero
image.layer.shadowRadius = 7.5
}
func videotext(string : String) ->Bool{
let videoextension = [".MP4",".mp4",".mkv",".MKV",".AVI",".avi",".mov", ".MOV"]
if videoextension.contains(string){
return true
}
return false
}
func videoThumb(filepath: URL) -> UIImage{
do{
// let filepath = data?.appendingPathComponent(lbl[indexPath.row])
let asset = AVURLAsset(url: filepath, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
let uiImage = UIImage(cgImage: cgImage)
return uiImage
}catch let error {
print("Error: \(error.localizedDescription)")
return UIImage()
}
}
private func handleSharedFile() {
// extracting the path to the URL that is being shared
let attachments = (self.extensionContext?.inputItems.first as? NSExtensionItem)?.attachments ?? []
let contentType = kUTTypeData as String
for provider in attachments {
// Check if the content type is the same as we expected
if provider.hasItemConformingToTypeIdentifier(contentType) {
provider.loadItem(forTypeIdentifier: contentType,
options: nil) { [unowned self] (data, error) in
guard error == nil else { return }
if let url = data as? URL {
imagesUrl.append(url)
print(imagesUrl)
if videotext(string: String(url.lastPathComponent.suffix(4))){
DispatchQueue.main.async {
self.image.image = videoThumb(filepath: url)
if attachments.count > 1 {
lbl.text = "\(attachments.count) Items"
}else{
lbl.text = url.lastPathComponent
}
}
}else {
let imageData = try? Data(contentsOf: url)
DispatchQueue.main.async {
if provider == attachments.last{
self.image.image = UIImage(data: imageData!)
}
self.singleImage = UIImage(data: imageData!)!
if attachments.count > 1 {
lbl.text = "\(attachments.count) Items"
}else{
lbl.text = url.lastPathComponent
}
}
}
}else {
print("Impossible to save image")
}
}
}
}
}
thank You in advance for read, giving attention, answer and upvote my question :)
I an application that suppose to get weather data in certain cities and I have a dropdown and based on the dropdown selection, an api should be called (based on city name), when I tap on a city for the first time the app runs it returns nil and if I tap on another city it returns data based on the first selection, I have debugged and traced the code line by line however the URL is correct and the everything seems to be in order, any help? here is my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tempraturevalue: UILabel!
#IBOutlet weak var cityname: UILabel!
#IBOutlet weak var temprature: UIImageView!
#IBOutlet var cityButtons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func handleSelection(_ sender: UIButton) {
cityButtons.forEach{ (button) in
UIView.animate(withDuration: 0.3) {
button.isHidden = !button.isHidden
self.view.layoutIfNeeded()
}
}
}
enum Cities:String {
case amman = "Amman"
case azzerqa = "Az zerqa"
case irbid = "Irbid"
case aqaba = "Aqaba"
}
var tempraturevalueData:Double = 0.0
var cityNameData:String = ""
#IBAction func cityTapped(_ sender: UIButton) {
guard let title = sender.currentTitle, let City = Cities(rawValue: title)
else {
return
}
var city:String
switch City {
case .amman:
city = "Amman"
case .azzerqa:
city = "zerqa"
case .irbid:
city = "Irbid"
case .aqaba:
city = "Aqaba"
}
let url = URL(string: "https://api.weatherapi.com/v1/current.json?key={key}&q=\(city)")
guard url != nil else {
print("error creating URL Object")
return
}
var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy , timeoutInterval: 10)
let headers = ["Content-Type" : "application/json"]
request.allHTTPHeaderFields = headers
request.httpMethod = "GET"
let session = URLSession.shared
let dataTask = session.dataTask(with: request, completionHandler: {(data, response, error) in
if error == nil && data != nil {
do {
let decoder = JSONDecoder()
do {
let weatherdatadecoded = try decoder.decode(WeatherData.self, from: data!)
self.tempraturevalueData = weatherdatadecoded.current?.temp_c ?? 0.1
self.cityNameData = weatherdatadecoded.location?.name ?? "no city found"
}
catch {
print(error)
}
}
catch {
print(error.localizedDescription)
}
}
})
dataTask.resume()
print(self.cityNameData)
print(self.tempraturevalueData)
}
}
I am trying to upload a picture picked by the user to firebase storage and then the url downloaded so the picture can be stored in realtime database, but have not been able to get it working with my code! I was originally going to use metadata!.downloadUrl() but that is no longer functional because of an update, so I am lost.
Here is my code:
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
class createPostViewController: UIViewController {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var contactEmail: UITextField!
#IBOutlet weak var contactPhoneNum: UITextField!
#IBOutlet weak var name: UITextField!
#IBOutlet weak var age: UITextField!
#IBOutlet weak var gender: UITextField!
#IBOutlet weak var lastSeen: UITextField!
#IBOutlet weak var profileDescription: UITextField!
#IBOutlet weak var postBtn: UIButton!
var imagePicker: UIImagePickerController!
var selectedImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(createPostViewController.handleSelect))
profileImage.addGestureRecognizer(tapGesture)
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
postBtn.layer.cornerRadius = 10
// Do any additional setup after loading the view.
}
#objc func handleSelect(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
#IBAction func post(_ sender: AnyObject) {
let userID = Auth.auth().currentUser?.uid
Database.database().reference().child("profiles").child(userID!).observe(.value, with: { (snapshot) in
let post: Dictionary<String, AnyObject> = [
// "userImg": as AnyObject,
"name": self.name.text as AnyObject,
"contactEmail": self.contactEmail.text as AnyObject,
"contactPhoneNum": self.contactPhoneNum.text as AnyObject,
"age": self.age.text as AnyObject,
"gender": self.gender.text as AnyObject,
"lastSeen": self.lastSeen.text as AnyObject,
"profileDescription": self.profileDescription.text as AnyObject,
]
let firebasePost = Database.database().reference().child("profiles").childByAutoId()
firebasePost.setValue(post)
})
}
func uploadImageToFireBase(image: UIImage) {
// Create the file metadata
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
let storageRef = Storage.storage().reference()
let profileRef = storageRef.child("images/rivers.jpg")
// Upload the file to the path FILE_NAME
Storage.storage().reference().child("FILE_NAME").putData(image.jpegData(compressionQuality: 0.42)!, metadata: metadata) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
print((error?.localizedDescription)!)
return
}
// Metadata contains file metadata such as size, content-type.
let size = metadata.size
print("Upload size is \(size)")
print("Upload success")
}
}
//func uploadToCloud(fileURL : URL) {
// let storage = Storage.storage()
//let data = Data()
//let storageRef = storage.reference()
//let localFule = fileURL
//let userID = Auth.auth().currentUser?.uid
//let photoRef = storageRef.child("profilePhoto\(userID)")
//let uploadTask = photoRef.putFile(from: localFule, metadata: nil) { (metadata, err) in
// guard let metadata = metadata else {
// print(err?.localizedDescription)
// return
//}
//print("Photo Upload")
// }
// }
}
extension createPostViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info["UIImagePickerControllerEditedImage"]as? UIImage {
selectedImage = image
print("success")
profileImage.image = image
uploadImageToFireBase(image: selectedImage)
} else {
print("image wasnt selected")
}
dismiss(animated: true, completion: nil)
}
}
I think you can still use the downloadUrl method on the storage reference.
func uploadImageToFireBase(image: UIImage) {
// Create the file metadata
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
// Upload the file to the path FILE_NAME
Storage.storage().reference().child("FILE_NAME").putData(image.jpegData(compressionQuality: 0.42)!, metadata: metadata) { (metadata, error) in
guard let metadata = metadata else {
print((error?.localizedDescription))
return
}
Storage.storage().reference().child("FILE_NAME").downloadURL { (imageUrl, error) in
if let error = error {
print("error: ", error.localizedDescription)
return
}
if let userID = Auth.auth().currentUser?.uid {
let currentUserRef = Database.database().reference().child("profiles").child(userID)
currentUserRef.updateChildValues(["profileImage": imageUrl])
}
}
}
}
Pls see this answer.
I just wanna make an iOS app with Instagram API then I can see the user profile.
I just wrote this Code on my Xcode project to make iOS app.
here is the code :--
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
signInRequest()
}
func signInRequest() {
let getURL = String(format: "%#?client_id=%#&redirect_uri=%#&response_type=token&scope=%#&DEBUG=True", arguments: [API.INSTAGRAM_AUTHURL,API.INSTAGRAM_CLIENT_ID,API.INSTAGRAM_REDIRECT_URI,API.INSTAGRAM_SCOPE])
let request = URLRequest.init(url: URL.init(string: getURL)!)
webView.loadRequest(request)
}
func checkRequestForCallbackURL(request: URLRequest) -> Bool {
let requestURLString = (request.url?.absoluteString)! as String
if requestURLString.hasPrefix(API.INSTAGRAM_REDIRECT_URI) {
let range: Range<String.Index> = requestURLString.range(of: "#access_token=")!
handleAuth(authToken: requestURLString.substring(from: range.upperBound))
return false
}
return true
}
func handleAuth(authToken: String) {
let url = String(format: "https://api.instagram.com/v1/users/self/?access_token=%#", authToken)
let request: NSMutableURLRequest = NSMutableURLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let session = URLSession(configuration: .default)
session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let data = data {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
let strFullName = (json?.value(forKey: "data") as AnyObject).value(forKey: "full_name") as! String
let secondVC: SecondViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondSeg") as! SecondViewController
secondVC.text = strFullName
self.present(secondVC
, animated: true, completion: nil)
}
}.resume()
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
return checkRequestForCallbackURL(request: request)
}
}
my question is when I run my app and want to see the instagram user username I can't see on my label.
I can't see the user (full_name, username, followers, etc...)
here is secondVC Code.
var text: String = ""
#IBOutlet weak var userNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
userNameLabel?.text = text
}
I believe your viewdidload function is being called before the update of your text variable
Try replacing:
var text: String = ""
With:
var text: String = "" {
didSet {
userNameLabel?.text = text
}
}
I am pretty much a beginner in Swift and I am trying to pass a value to make a call to an API with the value being from an input field.
The API is given below. How do I write code to pass value for ZIP_CODE from a text field?
https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/ZIP_CODE/JSON
#IBOutlet var zipLabel: UILabel!
#IBOutlet var zipInput: UITextField!
#IBOutlet var jsondataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
getJSON()
}
#IBAction func btnAction() {
zipLabel.text = zipInput.text
}
func getJSON(){
let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON")
let request = URLRequest(url: url as! URL )
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request){(data, response, error ) -> Void in
if error == nil{
DispatchQueue.main.async(execute: {
let jsondata = JSON(data : data!)
print(jsondata)
print("-----")
print(jsondata[0]["UV_INDEX"])
let result = jsondata[0]["UV_INDEX"].stringValue
self.jsondataLabel.text = result
})
}else{
print("There was an error")
}
}
task.resume()
}
func getJSON(_ zipcode : Int){
let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/\(zipcode)/JSON")
let request = URLRequest(url: url as! URL )
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request){(data, response, error ) -> Void in
if error == nil{
DispatchQueue.main.async(execute: {
let jsondata = JSON(data : data!)
print(jsondata)
print("-----")
print(jsondata[0]["UV_INDEX"])
let result = jsondata[0]["UV_INDEX"].stringValue
self.jsondataLabel.text = result
})
}else{
print("There was an error")
}
}
task.resume()
}
If your API gives you the response on GET Request you can use the following code -
#IBOutlet var zipLabel: UILabel!
#IBOutlet var zipInput: UITextField!
#IBOutlet var jsondataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnAction() {
zipLabel.text = zipInput.text
getJSON(zipcode: zipInput.text)
}
func getJSON(zipcode: String){
let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON&zipcode="+zipcode)
let request = URLRequest(url: url as! URL )
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request){(data, response, error ) -> Void in
if error == nil{
DispatchQueue.main.async(execute: {
let jsondata = JSON(data : data!)
print(jsondata)
print("-----")
print(jsondata[0]["UV_INDEX"])
let result = jsondata[0]["UV_INDEX"].stringValue
self.jsondataLabel.text = result
})
}else{
print("There was an error")
}
}
task.resume()
}
But Please note that this code won't work if your API gives you the response on POST request.