¿Por qué httpbody de NSMutableURLRequest cambia caracteres de mi string en swift?

Actualmente trabajo en un poryecto de swift en el que el usuario puede subir fotografias a un servidor, para lograr esto codifico la imagen capturada a base 64 esto lo consigo con el sguiente código:

func convertImageToBasee64(image: UIImage){     let imageData = image.jpegData(compressionQuality: 1)     let base64String = imageData!.base64EncodedString()     return base64String } 

Posteriormente creo la variable que uso como parámetro

let imagenEnviar = convertImageToBasee64(image: imagenVistaPrevia.image!) let parametros = "imagen=" + imagenEnviar 

y por último ejecuto la clase de conexion a mi server.

let conexion:clsConexionIA = clsConexionIA.init(url: "miurl.php", params: parametros) conexion.request{(output) in   print(output) } 

esta es mi clase de conexión:

class clsConexionIA {    let URL: String    let PARAMS: String     init(url: String, params: String) {        self.URL = url        self.PARAMS = params.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!    }     func request(successHandler: @escaping (_ response: String) -> Void)->Void{        let request = NSMutableURLRequest(url: NSURL(string: self.URL)! as URL)        request.httpMethod = "POST"        request.httpBody = self.PARAMS.data(using: String.Encoding.utf8, allowLossyConversion: false)        let headers = ["Content-Type": "application/x-www-form-urlencoded"]        request.allHTTPHeaderFields = headers         let task = URLSession.shared.dataTask(with: request as URLRequest) { datos, respuesta, error in            if error != nil {                successHandler(String(describing: error));            } else {                let responseString = NSString(data: datos!, encoding: String.Encoding.utf8.rawValue)                print("RESPUESTA \(responseString)")                successHandler((responseString as String?)!);            }        }        task.resume()    } } 

Mi problema es que del lado de mi servidor php estoy recibiendo una cadena que no es un base64 válido, por lo que la imagen se guarda corrupta-dañada.

He utilzado Charles Proxy para inspeccionar los parametros que le paso a mi servidor, y en notado que el string que se envía al server es distinto al que obtengo al inspeccionar en tiempo de ejecución la linea self.PARAMS.data(using: String.Encoding.utf8, allowLossyConversion: false)

¿a qué se debe esto y como puedo corregirlo? Yo imagino que la parte .data(using: String.Encoding.utf8, allowLossyConversion: false) hace alguna modificación a mi string, pero no he encontrado la forma de corregir esta situación. También he intentado obtener el .data sin el parámetro allowLossyConversion pero no noto cambio alguno.

Algunos de los cambios que noto en el string es, por ejemplo, que me reemplaza los caracteres + por espacios en blanco, también la longitud de caracteres es distinta, por lo que forzar un replace de espacios del lado del servidor no me funciona.

Se que hasta este punto self.PARAMS = params.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! mi string base64 es válido porque lo inspecciono en tiempo de ejecución, copio su valor y lo pego en algún decodificador online y la imagen se genera correctamente.

Espero y alguien pueda ayudarme, gracias de antemano comunidad!

CoreData, linking to C code with Swift on Linux [on hold]

I haven’t been able to determine this by reading stuff on Apple’s website, maybe someone here knows.

I am interested in writing Swift code on Linux. Now I know I can install Swift on Linux, that’s great. Does the Linux installation of Swift also include CoreData? That would be terrific.

Also, is it possible to compile C code and link it to Swift code on Linux, as it is possible on MacOS?

Thanks for any insights, I appreciate your help.

EDIT: I found this description: https://swift.org/blog/swift-linux-port/ but it is more than three years old at this point, so I guess I’m thinking that there has been a lot of progress since then.

Does Double Move allow you to cast spells or activate abilities that require swift or standard actions without changing weapon set up?

Can a character that, for example, holds a weapon in each hand, use its move action to sheathe one of them, cast a spell (a divine spell with the Quicken Spell metamagic feat which is a swift action) or activate an ability (Lay on Hands on himself which is another swift action) that’s shorter than a standard move with his now free hand, then turn his standard action into another move action and unsheathe the same weapon as before?

If that character also has a Bonus Attack higher than +1, would that mean that he would be able to move as well, during both of his move actions, at his normal speed each?

If that character also has Quick Draw, does that mean that he would be able to sheathe one of his weapons using his move action, cast a spell or activate an ability that requires a standard action instead, and unsheathe his weapon as a free action?

Crear un Array con números aleatorios y que no se repitan en Swift 4

mi pregunta es la siguiente: necesito generar un array con números aleatorios, pero que no se repitan los números, agradecería vuestra ayuda, muchas gracias.

for contador in 1...10    {      numerosAleatorios = Int.random(in: 1...100)      arrayNumeros.append(numerosAleatorios)      numerosAleatorios = 0     }  arrayNumeros.sort()  print(arrayNumeros) 

MVVM in Swift iOS

I’ve been implementing MVVM in Swift. I’ve looked at several implementations, many of which violate some aspects of MVVM and wanted to have a go with my own version that contains a Web request service.

View:

class BreachView: UIView {     var nameLabel = UILabel()     public override init(frame: CGRect) {         let labelframe = CGRect(x: 0, y: 50, width: frame.width, height: 20)         nameLabel.frame = labelframe         nameLabel.backgroundColor = .gray         super.init(frame: frame)         self.addSubview(nameLabel)         backgroundColor = .red     }      required init?(coder aDecoder: NSCoder) {         fatalError("init(coder:) has not been implemented")     } } 

ViewController class ViewController: UIViewController {

var breachesViewModel: BreachViewModelType! var breachView : BreachView?  // to be called during testing init(viewModel: BreachViewModelType) {     breachesViewModel = viewModel     super.init(nibName: nil, bundle: nil) }  // required when called from storyboard required init?(coder aDecoder: NSCoder) {     breachesViewModel = BreachViewModel()     super.init(coder: aDecoder) }  override func viewDidLoad() {     super.viewDidLoad()            breachesViewModel.fetchData{ [weak self] breaches in         guard let self = self else {return}         DispatchQueue.main.async {             self.updateUI()         }     } }  func updateUI() {     breachView = BreachView(frame: view.frame)     breachesViewModel.configure(breachView!, number: 3)     view.addSubview(breachView!) } 

}

Protocol for dependency injection:

protocol BreachViewModelType {     func fetchData(completion: @escaping ([BreachModel]) -> Void)     func configure (_ view: BreachView, number index: Int) } 

ViewModel class BreachViewModel : BreachViewModelType { var breaches = BreachModel

init() {     // add init for ClosureHTTPManager here, to allow it to be teestable in the future }  func fetchData(completion: @escaping ([BreachModel]) -> Void) {     ClosureHTTPManager.shared.get(urlString: baseUrl + breachesExtensionURL, completionBlock: { [weak self] result in         guard let self = self else {return}         switch result {         case .failure(let error):             print ("failure", error)         case .success(let dta) :             let decoder = JSONDecoder()             do             {                 self.breaches = try decoder.decode([BreachModel].self, from: dta)                 completion(try decoder.decode([BreachModel].self, from: dta))             } catch {                 // deal with error from JSON decoding!             }         }                 }) }  func numberItemsToDisplay() -> Int {     return breaches.count }  func configure (_ view: BreachView, number index: Int) {     // set the name and data in the view     view.nameLabel.text = breaches[index].name }  } 

and HTTP manager

    class ClosureHTTPManager {         static let shared: ClosureHTTPManager = ClosureHTTPManager()          enum HTTPError: Error   {         case invalidURL         case invalidResponse(Data?, URLResponse?)     }      public func get(urlString: String, completionBlock: @escaping (Result<Data, Error>) -> Void) {         guard let url = URL(string: urlString) else {             completionBlock(.failure(HTTPError.invalidURL))             return         }          let task = URLSession.shared.dataTask(with: url) { data, response, error in             guard error == nil else {                 completionBlock(.failure(error!))                 return             }              guard                 let responseData = data,                 let httpResponse = response as? HTTPURLResponse,                 200 ..< 300 ~= httpResponse.statusCode else {                     completionBlock(.failure(HTTPError.invalidResponse(data, response)))                     return             }              completionBlock(.success(responseData))         }         task.resume()     }     } 

Calling the API from

let baseUrl : String = "https://haveibeenpwned.com/api/v2" let breachesExtensionURL : String = "/breaches" 

Any comments on whether the implementation conforms to MVVM or not, typos, changes etc. are appreciated.

Git link: https://github.com/stevencurtis/MVVMWithNetworkService

No such module ‘IBMCloudAppID’ in xcode 10.2 Swift

I am trying to use IBMCloudAppId is my swift project and getting an error when I am trying to import IBMCloudAppID in my xcode 10.2.

I followed these steps as

  1. Open your Xcode project and enable Keychain Sharing (Under project settings > Capabilities > Keychain sharing)

  2. Under project setting > info > Url Types, Add $ (PRODUCT_BUNDLE_IDENTIFIER) as a URL Scheme

  3. Add the following import to your AppDelegate.swift file: import IBMCloudAppID

Getting an error

No such module 'IBMCloudAppID' in xcode 10.2 

And my POD file looks like

use_frameworks!  def shared_pods     platform :ios, '10.2'     pod 'BMSCore', '~> 2.3.1'     pod 'JOSESwift', '~> 1.1.0'     pod 'IBMCloudAppID' end  target 'IBMCloudAppID' do     use_frameworks!      pod 'IBMCloudAppID'      shared_pods end  target 'IBMCloudAppIDTests' do     shared_pods end 

swift NotificationCenter и pushViewController

В первом viewcontroller добавил наблюдателя, который меняет текст label

NotificationCenter.default.addObserver(self, selector: #selector(updatePrice), name: Constants.NotificationUpdatePrice, object: nil) ... @objc func updatePrice(){     self.recomendLabel.text = "11111" } 

Во втором viewController показываю первый и посылаю наблюдателю “зеленый свет”

self.navigationController?.pushViewController(viewcontroller, animated: true)  NotificationCenter.default.post(name: Constants.NotificationUpdatePrice, object: nil) 

Проблема в том, что когда первый viewcontroller показывается текст у него остается не изменным, немного продебажив понял, что метод updatePrice вызывается раньше, чем, например, метод viewWillAppear и из-за этого текст возвращается на изначальный.

Как можно решить эту проблему ?

Rsync: High write load in swift but no writing

I have following problem.

After replacing a broken HDD in my OpenStack/Swift node i have an issue. After putting in the new HDD and (re-)starting all of the needed services OpenStack/Swift starts the replication.

My monitoring tool then shows me that the network traffic goes up and that something is being written to the new HDD. iotop confirms what the monitoring showed before.

So far so good. The problem is that somehow nothing is being written. It seems like there is something being written on to the HDD but getting deleted directly after or at the same time.

Thanks in advance and hopefully someone can help me:)