gpt4 book ai didi

ios - 为什么我下载到同一个路径时得到不同的图像?

转载 作者:行者123 更新时间:2023-11-28 15:09:35 25 4
gpt4 key购买 nike

我正在尝试调试一段用于上传图片和从我自己的服务器下载该图片的代码。

图片路径为“http://localhost/Twitter/Avatar/52/avatar.jpeg

enter image description here

如我们所见,该文件夹中有两张图像,图像相同但名称不同。当我在下载图片时对路径进行硬编码时,我得到了一个奇怪的结果

 if avatarPath != nil {

let x = "http://localhost/Twitter/Avatar/52/avatar.jpeg"

let imageURL = URL(string: x)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: imageURL!, completionHandler: { (data, response, error) in

DispatchQueue.main.async {

if let imageData = data {
self.avatarImage.image = UIImage(data: imageData)
}
}

})

task.resume()
}



// round courner of avatar
avatarImage.layer.cornerRadius = avatarImage.bounds.width/20
avatarImage.clipsToBounds = true

//Give title to navigation controller
self.navigationItem.title = username.uppercased()



activityIndicator.stopAnimating()



}

当我写 let x = "http://localhost/Twitter/Avatar/52/pogba.jpeg "

我走和路径一样的图片,像这样

enter image description here

但是当我改成 let x = "http://localhost/Twitter/Avatar/52/avatar.jpeg "

我得到了不同的图像,像这样

enter image description here

我第一次上传图片的时候确实用过那个图片,但不知道为什么又出现了那个图片。我还没有实现缓存图像。为什么会这样?

这里是完整的源代码

import UIKit

class HomepageVC: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {


@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var fullnameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var editAvatarButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!



override func viewDidLoad() {
super.viewDidLoad()

activityIndicator.startAnimating()

// mendeklarasikan variable user yang berasal dari superglobal variable di appdelegate
let username = userInfo?["username"] as! String
let fullname = userInfo?["fullname"] as! String
let email = userInfo?["email"] as! String
let avatarPath = userInfo?["avatar"] as? String


// update user interface text & Label
usernameLabel.text = username.uppercased()
fullnameLabel.text = fullname.capitalized
emailLabel.text = email



// update user interface avatar

if avatarPath != nil {

let x = "http://localhost/Twitter/Avatar/52/pogba.jpeg"

let imageURL = URL(string: x)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: imageURL!, completionHandler: { (data, response, error) in

DispatchQueue.main.async {

if let imageData = data {
self.avatarImage.image = UIImage(data: imageData)
}
}

})

task.resume()
}



// round courner of avatar
avatarImage.layer.cornerRadius = avatarImage.bounds.width/20
avatarImage.clipsToBounds = true

//Give title to navigation controller
self.navigationItem.title = username.uppercased()



activityIndicator.stopAnimating()



}





@IBAction func logoutButtonDidPressed(_ sender: Any) {

//menghapus data userDefault yang sudah ada
UserDefaults.standard.removeObject(forKey: "parsedJSON")
UserDefaults.standard.synchronize()

//menuju ke login page dengan modal segue
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginVC = storyboard.instantiateViewController(withIdentifier: "loginVC")
present(loginVC, animated: true, completion: nil)

}



@IBAction func editProfilePictureButtonDidPressed(_ sender: Any) {

// user akan memilih photo dari library atau dari camera nya


let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true



let actionSheet = UIAlertController(title: "Photo Source", message: "please choose your source", preferredStyle: .actionSheet)


// action camera
let actionCamera = UIAlertAction(title: "Camera", style: .default) { (action) in

if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)

} else {
self.showAlert(alertTitle: "Opppss", alertMessage: "camera can't be used / not available", actionTitle: "OK")
print("camera can't be used / not available")
}

}


// action photo library
let actionPhotoLibrary = UIAlertAction(title: "Photo Library", style: .default) { (action) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}


//action cancel
let actionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)


actionSheet.addAction(actionCamera)
actionSheet.addAction(actionPhotoLibrary)
actionSheet.addAction(actionCancel)


self.present(actionSheet, animated: true, completion: nil)



}






func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {


let image = info[UIImagePickerControllerOriginalImage] as! UIImage
avatarImage.image = image
picker.dismiss(animated: true, completion: nil)



// call func of uploading file to server
uploadAvatar()

}




func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}






// custom HTTP request body to upload image file
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {

var body = Data();

if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}

// kita set agar image yang di upload kemudian berformat .jpg
let filename = "avatar.jpeg"

let mimetype = "image/jpeg"

body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey)
body.appendString("\r\n")

body.appendString("--\(boundary)--\r\n")

return body as Data

}


// uploading image ke server
func uploadAvatar() {



// mendapatkan ID dari User Default variable
let id = userInfo!["id"] as! String


// membuat request
let url = URL(string: "http://localhost/Twitter/uploadAvatar.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"


// parameter yang akan dikirim di dalam request body
// parameter ini dibutuhkan karena uploadAvatar.php membutuhkan inputan ID
let param = ["id" : id]

// membuat Boundary
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


// mengassign image yang akan di upload dan melakukan kompresi
let imageData = UIImageJPEGRepresentation(avatarImage.image!, 0.5)

// if not compressed, return ... do not continue to code
if imageData == nil {
return
}





// constructing http body
request.httpBody = createBodyWithParams(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)

// filePathKey berupa 'file' agar nanti di PHP $_FILES bisa didentifikasi, contohnya $_FILES['file'][tmp_name]


// launc session
URLSession.shared.dataTask(with: request) { data, response, error in




DispatchQueue.main.async(execute: {

if error == nil {

// maka tampilkan $returnArray dari PHP (response message from server)

do {

// json containes $returnArray from php
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

// declare new parseJSON to store json
guard let parsedJSON = json else {
print("Error while parsing")
return
}


print(parsedJSON)

// get id from $returnArray["id"] in PHP - parseJSON["id"]
let id = parsedJSON["id"]

// successfully uploaded
if id != nil {

// save user information yang berasal dari server
UserDefaults.standard.set(parsedJSON, forKey: "parsedJSON")
userInfo = UserDefaults.standard.object(forKey: "parsedJSON") as? NSDictionary





// jika tidak ada "id" kiriman dari server, maka ada error message
} else {

// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = parsedJSON["message"] as! String
self.showAlert(alertTitle: "opppps", alertMessage: message, actionTitle: "OK")
})

}



// error ketika melakukan JSON serialization
} catch {

// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error.localizedDescription
self.showAlert(alertTitle: "SorryBroooo", alertMessage: message, actionTitle: "OK")
})

}

// error ketika koneksi ke server
} else {

// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
self.showAlert(alertTitle: "oppps", alertMessage: message, actionTitle: "OK")
})

}


})

}.resume()


}






}







// extend data
extension Data {

mutating func appendString(_ string : String) {

let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)

}

}

最佳答案

当您使用此代码时

let session = URLSession(configuration: .default)

您已自动注册默认缓存策略,它使用此链接中指定的基于永久磁盘的缓存: https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1411560-default

如果你想删除所有缓存策略,请改用此代码

let session = URLSession(configuration: .ephemeral)

关于ios - 为什么我下载到同一个路径时得到不同的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47897589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com