xamarin UTF8Encoding string to NSURL - utf-8

i need to open a Webview that translate some word from chinese to English , i am doing like this
string urlString = "https://translate.google.com.tw/#zh-CN/en/中文測試";
NSUrl url = new NSUrl(urlString);
NSUrlRequest request = new NSUrlRequest(url);
WebViewController transView = new WebViewController(request);
it should open the url https://translate.google.com.tw/#zh-CN/en/中文 , but will show "the native 'initWithString:'" method returned nil , i think i should doing some encode to my urlString.
i try to change my code like this
string urlString = "https://translate.google.com.tw/#zh-CN/en/";
urlString = urlString + HttpUtility.UrlEncode("中文測試",Encoding.UTF8);
NSUrl url = new NSUrl(urlString);
NSUrlRequest request = new NSUrlRequest(url);
WebViewController transView = new WebViewController(request);
but the WebView only open "https://translate.google.com.tw/#zh-CN/en/" , my encoding part not handled.

Related

Swift 3.1 How to insert image as base64 into body of HTTPS request

I want to send an image to server using HTTPS POST request. I need to send image as base64 data. I have converted image data to base64 encoded string, but I cannot convert it to Data to put it into httpBody.
//encode image to base64
let chosenImage = imageView.image
let imageData:NSData = UIImagePNGRepresentation(chosenImage!)! as NSData
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
let dataBase64: Data = Data(strBase64)
let uploadUrlString = "https://api.imgur.com/3/upload"
let uploadUrl = NSURL(string: uploadUrlString)
let uploadRequest = NSMutableURLRequest(url: uploadUrl! as URL)
uploadRequest.addValue("Client-ID f7e5521d5dd4245", forHTTPHeaderField: "Authorization")
uploadRequest.httpMethod = "POST"
uploadRequest.httpBody = imageData
let uploadSession = URLSession.shared
let postRequest = uploadSession.dataTask(with: uploadRequest as URLRequest) { (data, response, error) -> Void in
if let antwort = response as? HTTPURLResponse {
let code = antwort.statusCode
print(code)
}
}
postRequest.resume()
Saw some solutions on StakOverflow, but didn't get how to do it properly.
Please advise.
I had the same problem ... here is my solution to insert BASE64 String into email-body:
//SWIFT 3.x
//convert to Data
let image = UIImage(data: yourUIImage! as Data)
//convert to base64 String
let imageData: NSData = UIImagePNGRepresentation(image!)! as NSData
let imageStr = imageData.base64EncodedString(options:.endLineWithCarriageReturn)
// insert this into your HTML code
let tmpHTMLimage = "<img class=\"no-show\" src=\"data:image/png;base64," + imageStr + "\" alt=\"Image\" height=\"80\" width=\"80\"/>"
solution: use .endLineWithCarriageReturn and not
.lineLength64Characters!!!
I realy hope this will help some of you guys!
Finally I have changed code a bit according to some advised from Leo Dabus. And I have ensured that it works fine without any conversion to base64:
let chosenImage = imageView.image
let imageData = UIImageJPEGRepresentation(chosenImage!, 1)
let uploadUrlString = "https://api.imgur.com/3/upload"
let uploadUrl = URL(string: uploadUrlString)
var postRequest = URLRequest.init(url: uploadUrl!)
postRequest.addValue("Client-ID XXXXXX", forHTTPHeaderField: "Authorization")
postRequest.httpMethod = "POST"
postRequest.httpBody = imageData
let uploadSession = URLSession.shared
let executePostRequest = uploadSession.dataTask(with: postRequest as URLRequest) { (data, response, error) -> Void in
if let response = response as? HTTPURLResponse
{
print(response.statusCode)
}
if let data = data
{
let json = String(data: data, encoding: String.Encoding.utf8)
print("Response data: \(String(describing: json))")
}
}
executePostRequest.resume()
So when uploading an image, I'm getting body of the result in json and it shows me the link to uploaded image:
"link\":\"http:\\/\\/i.imgur.com\\/ePOUIyN.jpg\"},\"success\":true,\"status\":200}")

Array of files from directory

I have the following code working on playground, and I get the array at imageURLs.
let imagePath = str
let url = NSURL(fileURLWithPath: imagePath)
let fileManager = FileManager.default
let properties = [URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
let imageURLs = try fileManager.contentsOfDirectory(at: url as URL, includingPropertiesForKeys: properties, options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
Then I add "do" "catch" to handle the errors on the project but it stops working.
let imagePath = Gal.urlDirectorio
let url = NSURL(fileURLWithPath: imagePath)
let fileManager = FileManager.default
let properties = [URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
do { imageURLs = try fileManager.contentsOfDirectory(at: url as URL, includingPropertiesForKeys: properties, options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
} catch {
}
I follow the debugging process and everthing works until the "do" line. I have no error but it doesn't add the urls to the array.

Reading a RTF file and parse plaintext

I am doing this to get the content of a file using NSOpenPanel, but I am getting a lot of weird stuff returned from the .rtf file I select.
My panel code:
var panel: NSOpenPanel = NSOpenPanel()
var fileTypesArray: NSArray = ["txt", "rtf", "nil"]
panel.canChooseFiles = true
panel.allowedFileTypes = fileTypesArray as [AnyObject]
panel.allowsMultipleSelection = false
if panel.runModal() == NSModalResponseOK {
var url = panel.URL!.path
println(url)
let path = url
let expandedPath = path!.stringByExpandingTildeInPath
let data: NSData? = NSData(contentsOfFile: expandedPath)
if let fileData = data {
let content = NSString(data: fileData, encoding:NSUTF8StringEncoding) as! String
println(content)
}
}
The contents of my .rtf document is "Testing 123"
This is what is being printed to the console:
{\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\f0\fs24 \cf0 Testing 123\
}
Is there any way I can get just the text from the file, and what is all the other stuff that is being printed?
That "other stuff" is the actual RTF data.
I would recommend using the NSAttributedString initializer NSAttributedString(path:documentAttributes:), which will read in and process the RTF data. Then you can access the plain text by using attributedString.string.
In your case, it would be
if let content = NSAttributedString(path: expandedPath, documentAttributes: nil) {
// do something with content or content.string
}

Making Amazon Web Services S3 POST request in Swift

I am trying to use AWS S3 service to host images of my iOS application in Swift language.
At this step I am just trying to simply post png image with POST request.
In any POST request for AWS S3 we need to make an authorization header which consists of the information that authenticate this request. To encode data with HMAC SHA256 which is required by Amazon I use GitHub project as my Subproject from this link: https://github.com/krzyzanowskim/CryptoSwift
This helped me to encrypt the signature however when I tried to send this request I received an error which says: "SignatureDoesNotMatchThe request signature we calculated does not match the signature you provided. Check your key and signing method."
Here is my code:
var img = UIImage(named: "myImage.png")
var imageData : NSData = UIImageJPEGRepresentation(img, 1.0)
let key = "mybucketname"
let url = NSURL(string:"http://mybucket.s3.amazonaws.com/")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let uniqueId = NSProcessInfo.processInfo().globallyUniqueString
var postBody:NSMutableData = NSMutableData()
var boundary:String = "------WebKitFormBoundary\(uniqueId)"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField:"Content-Type")
// I am trying to generate a date stamp compatible for request
let date = NSDate()
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
formatter.stringFromDate(date)
var dateKey = ["AWS4"+"My AWSSecretKey","20150317"]
// Here is the signature that I'm trying to make
var signature = "My AWSSecretKey".sha256()?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
request.addValue("AWS MYAWSACCESSKEYID:\(signature)", forHTTPHeaderField: "Authorization")
request.addValue("Wed, 18 Mar 2015 20:39:27 +0000", forHTTPHeaderField: "Date")
request.addValue(key, forHTTPHeaderField:"key")
request.addValue("\(postBody.length)", forHTTPHeaderField:"Content-Length")
postBody.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
postBody.appendData("Content-Type: image/png\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
postBody.appendData(imageData)
var postData = String()
postData += "\r\n"
postData += "\r\n--\(boundary)--\r\n"
postBody.appendData(postData.dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = postBody
var error: NSError?
let session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, err) -> Void in
var stringData = NSString(data: data, encoding: NSUTF8StringEncoding)
var conversionError: NSError?
var jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: &conversionError) as? NSDictionary
})
task.resume()
I need to find out how to make a proper signature and how I should encrypt it since its my fire time using such tools.
You shouldn't have a secret key hard-coded in your app - this negates its security. I'd suggest generating the key from your own server (eg using the excellent S3Direct django module), then obtain the key like this:
let filename = "myfile.mp4"
let requestUrl = Constants.my_own_server+"/s3direct/get_upload_params/"
println("Uploading file of name ***" + filename + "***")
let defaults = NSUserDefaults.standardUserDefaults()
let authToken : String = defaults.stringForKey("token")!
let manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
"Authorization": "Token " + authToken
]
let parameters : [ String : AnyObject] = [
"type": "video/mp4",
"name": filename,
"dest": "vids"
]
Alamofire.request(.POST, requestUrl, parameters: parameters).response(serializer: Request.JSONResponseSerializer(), completionHandler: { (request, response, object, error) -> Void in
//println(object)
//println(error)
if (error == nil) {
self.uploadFile(videoData!, parameters: object as! [ String : String], filename: filename)
}
else {
print("Failed to sign file")
}
})
Good luck - I have found this particular stack unusually painful to get working.

Converting PathForResource To String Returning nil Swift

When loading a local resource file in a mac app
let urlpath = NSBundle.mainBundle().pathForResource("myResource", ofType: "html");
Converting the resource path to a string for NSURL always returns nil
println("resource path = \(urlpath)") <---resource logged ok
web.frameLoadDelegate = self;
let requesturl = NSURL(string: urlpath!)
println("URL String = \(requesturl)"),<---- returns nil
let request = NSURLRequest(URL: requesturl!)
web.mainFrame.loadRequest(request)
Which presumably is why im getting the error found nil while unwrapping an Optional value
What am I missing here to correctly convert the pathForResource to a string?
if let myFileUrl = NSBundle.mainBundle().URLForResource("yourFile", withExtension: "html"){
// do whatever with your url
}
The code given in Leonardo's answer should work and is the easier and safer
method with optional binding. Here is an explanation why your
code fails:
let requesturl = NSURL(string: urlpath!)
returns nil because urlpath is a file path and not an URL string
(such as "file:///path/to/file").
If you replace that line with
let requesturl = NSURL(fileURLWithPath: urlpath!)
then you will get the expected output.
For Swift 5
let path = Bundle.main.path(forResource: "myResource", ofType: "html")
let url = URL(fileURLWithPath: path!)

Resources