Multipart form-data file uploading using Alamofire - swift

I have looked at questions like this or that one but it is still not working.
Also I have a question about what should I enter into fileURL param from function multipartFormData.appendBodyPart?
Should it be a way to image from PC, or image must be added to Images.xcassets? What should I send here?

It looks like you have three issues that you need to fix.
Use .POST instead of POST.
The fileURL needs to be a valid NSURL that points to a file on the file system. You cannot just use the filename.
You are using the responseString serializer, but named the third parameter in the closure JSON. Then you are letting result into s and trying to print it out. The result parameter doesn't even exist anywhere. Instead, you should print(JSON).
Hopefully that helps clear things up a bit.

Try to use .POST not POST
As an alternative solution upload an encoded file and send it as a parameter of POST.
// `data` is NSData
let base64String = data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
let parameters = ["image_data": base64String] as [String: AnyObject]
Alamofire.request(.POST, "http://your-url.com", parameters: parameters)
The cons of this method is that the data will get %33 larger due to encoding. If you have bandwidth problems it may not be a good solution.

Related

URL - Found nil while unwrapping an Optional value

I'm a little ashamed to post this as I use URLs all the time but this one has me stumped!
I keep getting an 'Unexpectedly found nil while unwrapping an Optional value'
Just to add some context, I use the same format for over 20 URLs which is making requests to an API. The only difference is the ID at the end of the URL.
Ignore the insecure URL as this is simply a debug endpoint and has no bearing on the issue as I use the same URL in other calls. Also, ignore the first part of the URL, I have purposefully changed it for security purposes.
The code I use is as follows:
func returnEventParticipantsEndPoint(eventID: String) -> URLRequest {
print("URL: \(debugEndPointURL)/api​/friendgroups​/\(eventID)")
var url: URL!
url = URL(string: "\(debugEndPointURL)/api​/friendgroups​/\(eventID)")!
let requestURL = URLRequest(url: url)
return requestURL
}
The URL printed in the console (top line) before I try to return the URLRequest prints as follows:
http://blahblahblah.blah.net/api​/friendgroups​/1c8264b95884409f90b4fd8ba9d830e1
Yet, it keeps returning nil and I'd really appreciate some help with this...thanks.
The reason that it is failing is that there are hidden Unicode characters in your string. Copying and pasting the url string you provided into a hidden Unicode character checker gives the following for your url
http://blahblahblah.blah.net/apiU+200B​/friendgroups​U+200B/1c8264b95884409f90b4fd8ba9d830e1
Notice the additional hidden characters at the end of the words api and friendgroups
You can try it here https://www.soscisurvey.de/tools/view-chars.php
Have you copied and pasted the format for this? Examining the string you have some non printable Unicode characters after the words api and friendgroups. Retyping the url path and trying again worked for me

Weird output from URL html source Swift

Basically I'm trying to download the HTML source code of a URL object into a String...
I've followed step-by-step examples of how-to-do so on StackOverflow.
import Foundation
try! print(String(contentsOf: URL(string: "https://www.google.com")!, encoding: .utf16))
This is a small sample of the output I'm getting:
楤瑨㨱〰╽䁭敤楡⁡汬笮杢ㅻ桥楧桴㨲㉰砻浡牧楮⵲楧桴㨮㕥活癥牴楣慬ⵡ汩杮㩴潰紣杢慲筦汯慴
When I was really just expecting some plain HTML output.
The only thing I could think that's causing this issue has to be related to Networking(such as the DNS servers being queried). But, just in case I'm asking it on here to get a review of the code.
It's unclear why you want to encode the output to UTF-16, although removing it should work:
try! print(String(contentsOf: URL(string: "https://www.google.com")!))
That should return the html of the URL.
You can use an encoding, however, UTF-16 is likely not correct in this circumstance.
try! print(String(contentsOf: URL(string: "https://www.google.com")!, encoding: .ascii))
ASCII would likely work.

Using NSURLSession (in Swift) to get data

I've been searching around to learn how to get some data using NSURLSession in Swift.
There is a general pattern being repeated on the internet for making an http request using NSURLSession, and it looks a lot like this:
let url = NSURL(string: "myPretendURLthatIsNotThisURL.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding))}
task.resume()
If I place a real URL in, I can see a lot of JSON output printed, which is the expected response from the server. Nice : ) I can see the data from println(). However, I would rather display the returned data in a text view when I press a button. I do believe my solution relies on using a delegate (somehow).
Is it all right to request an example of how this is done, in the following context:
Code is in Swift
Press a button (IBAction, contains the code above to make the request)
Display the data returned (it's JSON, I'll worry how to parse it later on) in a text view.
Thanks!

Objective C error 3840 - bad JSON apparently but it validates with JSlint

I have read around and this error seems to be from bad JSON. Easy enough, here is my JSON
{"year":"2012","wheels":"Standard","trans":"Unknown"}
My issue is, this appears to be correct, and when I run it through JSON lint it returns vaild. I have also used cURL to download this page and used json_decode() to read it...worked fine.
Here is an example page: http://drivingthenation.com/app/carlist/getVinDtn.php?v=JA3215H1C**M&f=v
I ran it through HTTPScoop and the only thing the response text returned was
{"year":"2012","wheels":"Standard","trans":"Unknown"}
On the objective-c end I am using NSURL and NSData to get the URL, and then NSJSONSerialization. I can print out before NSJSONSerialization and see that it is infact getting data, but this error only occurs when I try to format it into JSON. Any thoughts?
The NSJSONSerialization class, by default, expects the input to be not just valid JSON, but a valid JSON object. If you want to read something that's not an object, you need to specify the NSJSONReadingAllowFragments option to the reader.

iPhone json parsing problem

When I try to parse ( http://www.roundmenu.com/webservices/index.cfm?ws=listrst&filter=featured ) webservice in json I encounter issues.
If any one can find out what the problem please let me know.
thanks in advance.
That’s not valid JSON. As usual, it’s useful to validate JSON input via http://jsonlint.com.
That particular JSON input fails to properly escape double quotes (\") inside strings.
Put the response in a json formatter like this one on curiousconcept.com. It yields many errors, does look like it's invalid json.