Upload picture using alamofire - ios

so my doubt is on how to upload an image using Alamofire, from what researched people uses the solutions here https://github.com/Alamofire/Alamofire/issues/110. However my curl request should look like this:
curl -X POST "api.local.app.com:9000/1/media/upload" -F “picture=#filename.png” -H “Authorization: Alpha ahudhasiadoaidjiajdiudaiusdhuiahdu” -v
I'm trying to do that this way:
Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization" : "Alpha \(userToken)" ]
var fileManager = NSFileManager()
var tmpDir = NSTemporaryDirectory()
let filename = "tempPicture.png"
let path = tmpDir.stringByAppendingPathComponent(filename)
var error: NSError?
let imageData = UIImagePNGRepresentation(image)
fileManager.removeItemAtPath(path, error: nil)
println(NSURL(fileURLWithPath: path))
if(imageData.writeToFile(path,atomically: true)){
println("Image saved")
}else{
println("Image not saved")
}
Alamofire.upload(.POST, databaseURL + "/media/upload", NSURL(fileURLWithPath: path)!).progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println( String(totalBytesWritten) + "/" + String(totalBytesExpectedToWrite))
}
.responseJSON { (request, response, data, error) in
From what I understand this should work however the Alamo returns
Error: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The
operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value
around character 2.) UserInfo=0x7e16d9e0 {NSDebugDescription=Invalid
value around character 2.}).

I have already provided a detail answer here. Most likely your server expects the image to be multipart form data encoded which is why it is getting rejected. There are many details provided in that link, along with next steps.

Related

"The file “command.cgi” couldn’t be opened."

FlashAir W-04 Fourth Generation SD memory card
In my iOS app directory listing api not working.
Response :
Task .<0> HTTP load failed (error code: -1003 [12:8])
2019-05-21 23:32:40.267572+0530 Razzo[10489:87069] NSURLConnection finished with error - code -1003
Error Domain=NSCocoaErrorDomain Code=256 "The file “command.cgi” couldn’t be opened." UserInfo={NSURL=http://flashair/command.cgi?op=100&DIR=/DCIM}
Please help me what was wrong
below code snippet
private func getdata() {
let url100 = URL(string: "http://flashair/command.cgi?op=100&DIR=/DCIM")
var dirStr: String? = nil
do {
if let url100 = url100 {
dirStr = try String(contentsOf: url100, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
if let dir = dirStr {
arrayfiles = dir.components(separatedBy: "\n")
}
tblContent.reloadData()
}
} catch {
print(error)
self.displayAlert(message: error.localizedDescription)
}
}
Config file below
[Vendor]
CIPATH=/DCIM/100__TSB/FA000001.JPG
APPMODE=4
APPNETWORKKEY=12345678
VERSION=F15DBW3BW4.00.03
CID=02544d535733324755e3c6dc7b012301
PRODUCT=FlashAir
VENDOR=TOSHIBA
MASTERCODE=f437b71e0e4f
LOCK=1
contentsOf: url100 would be for a local file URL. You are not providing a valid file URL.
If your file is remote you need to download the file as data with URLSession. If it is local you need to work out its file URL.

What is solution for "The file couldn’t be opened." UserInfo={NSURL=ftp:/xxxx:xxx#2011#ftp.xxx.com:21/}?

I am trying to call FTP server api and want to get file name when api is success.
Below code I tried for call api,
let host = "ftp.xxx.com"
let user = "xxx"
let password = "xxx#2011"
let port = "21"
let url = URL(string: "ftp://"+user+":"+password+"#"+host+":"+port+"/")
var data: Data? = nil
do {
if let anUrl = url {
data = try Data(contentsOf: anUrl)
print(data!)
}
} catch {
print("Unexpected error: \(error).")
}
When run this code I am getting error like
Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo={NSURL=ftp:/xxxx:xxx#2011#ftp.xxx.com:21/}.
Please give me any solution to solve this.
The problem is the plain # inside the password. This means ftp://xxxx:xxx#2011#ftp.xxx.com:21/ gets interpreted as connecting to server 2011#ftp.xxx.com with username xxxx and password xxx, which is obviously wrong.
The solution should be to URL-encode the special character # to %40, i.e. use the URL
ftp://xxx:xxx%402011#ftp.xxx.com:21/

Corruption of contentsURL encoding type?

I am still struggling with accessing certain Google pages and have tried multiple combinations of encoding types. I've also tried UTF8 and then falling through to a default if that fails. This is where things get very odd.
I do the following:
println("URL within process page = \(url)")
println("Trying NSUTF8")
origURLString = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)
if (error != nil) {
println("Error = \(error)")
println("Trying NSASCII next")
origURLString = String(contentsOfURL: url, encoding: NSASCIIStringEncoding, error: &error)
if (error != nil) {
println("Error = \(error)")
}
}
if (error != nil) {
return "There seems to be a problem going to this site"
}
Both calls to contentsOfURL fail with the following trace:
Trying NSUTF8
Error = Optional(Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x7fbbda599b00 {NSURL=http://www.google.com/search?ie=ISO-8859-1&hl=en-GB&source=hp&q=hello&btnG=Google+Search&gbv=1, NSStringEncoding=4})
Trying NSASCII next
Error = Optional(Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x7fbbda599b00 {NSURL=http://www.google.com/search?ie=ISO-8859-1&hl=en-GB&source=hp&q=hello&btnG=Google+Search&gbv=1, NSStringEncoding=4})
However, if I don't try using NSUTF8StringEncoding and just use ASCII encoding:
origURLString = String(contentsOfURL: url, encoding: NSASCIIStringEncoding, error: &error)
Then this works (not so well since the encoding isn't right). No error code at least, and I get a full HTML page.
Obviously, I can't use ASCII encoding for everything and I would rather build a general approach that checks UFT8 first before defaulting to something else.
Am I corrupting something with my first approach? Is the error message carrying over?
I tried testing every NSEncodingType in a loop and that failed, so I narrowed it down to just two and I get the same issue.
Ideas? I'm at a complete loss.
This function helps me correct my text strings:
func utf(txt:String)->NSString{
var newtxt = txt.stringByReplacingOccurrencesOfString("\\n", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil)
if var scb = NSString(CString: newtxt ,encoding:NSNonLossyASCIIStringEncoding){
return scb
}else{
var scb = NSString(CString:newtxt, encoding:NSUTF8StringEncoding)
return scb!
}
}
This is interesting because it occupies the encoding that fits
according to the text string to be sent.

How can I get source code from URL with SSL using Swift?

I am trying to read a source code of a site from its URL.
Below is my code.
let myURLString = "https://theUrlOfTheSite"
let myURL = NSURL(string: myURLString)
var error: NSError?
let myHTMLString = String(contentsOfURL: myURL!, encoding: NSUTF8StringEncoding, error: &error)
if let error = error {
println("Error : \(error)")
} else {
println(myHTMLString)
}
It works for some site, but not for others. I get the following error
2014-12-21 19:11:54.032 MyPlayground[2912:345862] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)
Error : Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)"
I think it's because the site is https, not http. (I don't really know about this stuff but..SSL something??)
So my question is, what should I do to make my code work??
I searched for hours but I'm new to iOS and Swift, so no progress.
Do I have to make NSURLConnection or something? Because all I want to do is get the source code. Must be a simple job I guess..
Any help will be appreciated. Thanks in advance.

plist attachment from email in swift (NS Cocoa Error Domain Code 260)

I am sending some ios file data via an email contained in a plist. No issues attaching it, I can check the file and the contents. It's all there and I can open it as a plist. Clicking on it (I have associated it with my app) it opens and I get a valid path:
file:///private/var/mobile/Containers/Data/Application/C5454580-2BEB-4515-9BDE-FED85FF54F76/Documents/Inbox/ShareStrength-11.bps
that I pass but when I try and read back the NSDictionary (plist) I get nil content.
let sourceFile = NSDictionary(contentsOfFile: URLString)
Any ideas on what is going wrong. Having difficulty debugging.
EDIT: I found some error code:
var error: NSError?
let content = NSString(contentsOfFile: URLString, encoding:NSUTF8StringEncoding, error: &error)
if content != nil
{
println("content: \(content)")
}
else
{
println("error: \(error)")
}
And I get the error:
error: Optional(Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x17eceeb0 {NSFilePath=file:///private/var/mobile/Containers/Data/Application/571DB0FF-6C5A-4BEB-9FA8-6E4DFE10E850/Documents/Inbox/ShareStrength-13.bps, NSUnderlyingError=0x17ee9810 "The operation couldn’t be completed. No such file or directory"})
Is this a sandbox issue? How can I copy the attachment being passed as a URL?
I was using:
let URLString: String = url.absoluteString!
instead of:
let URLString: String = url.path!
Hope this helps someone else

Resources