ALAMOFIRE response image data for multipart image - iphone

I have written a function which uploads two multipart images on the server and the server merges these 2 images and returns 1 whole image as response.
This is the function
func apiObjectInPainting(image: UIImage, maskedimage: UIImage,completion: #escaping (Bool) -> Swift.Void) {
if let data = UIImageJPEGRepresentation(image,1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("image1.jpg")
try? data.write(to: filename)
}
if let data = UIImageJPEGRepresentation(maskedimage,1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("image2.jpg")
try? data.write(to: filename)
}
let fileURL1 = getDocumentsDirectory().appendingPathComponent("image1.jpg")
let fileURL2 = getDocumentsDirectory().appendingPathComponent("image2.jpg")
NSLog("Files being stored #\(fileURL1)")
KVNProgress.show(withStatus: "Replacing Object")
Alamofire.upload(multipartFormData:{ multipartFormData in
multipartFormData.append(fileURL1, withName: "image")
multipartFormData.append(fileURL2, withName: "image")
multipartFormData.append("SECKEY".data(using: .utf8)!, withName: "Authorization")
},
usingThreshold:UInt64.init(),
to:"[URL]",
method:.post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { response in
debugPrint(response)
KVNProgress.dismiss()
completion(true)
}
case .failure(let encodingError):
KVNProgress.dismiss()
print(encodingError)
}
})
}
In encodeCompletion I have
case .success(let upload, _, _):
upload.response { response in
debugPrint(response)
KVNProgress.dismiss()
completion(true)
}
But in the response I get,
Alamofire.DefaultDataResponse(request: Optional([URL]), response: nil, data: Optional(0 bytes), error: Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x600000446450 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=[URL], NSErrorFailingURLKey=[URL], _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}), timeline: Timeline: { "Request Start Time": 509658047.051, "Initial Response Time": 509658047.386, "Request Completed Time": 509658166.018, "Serialization Completed Time": 509658166.021, "Latency": 0.335 secs, "Request Duration": 118.967 secs, "Serialization Duration": 0.003 secs, "Total Duration": 118.970 secs }, _metrics: Optional((Task Interval) <_NSConcreteDateInterval: 0x6000004223c0> (Start Date) 2017-02-24 19:40:47 +0000 + (Duration) 118.966891 seconds = (End Date) 2017-02-24 19:42:46 +0000
(Redirect Count) 0
(Transaction Metrics) (Request) <NSURLRequest: 0x600000016020> { URL: [URL] }
(Response) (null)
(Fetch Start) 2017-02-24 19:40:47 +0000
(Domain Lookup Start) 2017-02-24 19:40:47 +0000
(Domain Lookup End) 2017-02-24 19:40:47 +0000
(Connect Start) 2017-02-24 19:40:47 +0000
(Secure Connection Start) (null)
(Secure Connection End) (null)
(Connect End) 2017-02-24 19:40:47 +0000
(Request Start) 2017-02-24 19:40:47 +0000
(Request End) 2017-02-24 19:41:47 +0000
(Response Start) 2017-02-24 19:40:47 +0000
(Response End) (null)
(Protocol Name) http/1.1
(Proxy Connection) NO
(Reused Connection) NO
(Fetch Type) Network Load
))
Please help me in getting proper response as currently it is not successfull.

Its seems you are uploading large amount of data, so your request is timeout. You can increase timeout interval and its work for you.
Here is the code:
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForResource = 10800 // seconds
configuration.timeoutIntervalForRequest = 10800 // seconds
alamoFireManager = Alamofire.Manager(configuration: configuration)
Happy Coding :)

Related

HTTP Status NIL using both URLSession and AlamoFire. Error Code=303 and NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask

What's Expected:
Response with status code 200 and a JSON body with auth token etc.
What's Happening:
A device will (randomly?) no longer make the login call to auth0 successfully.
HTTP status code, response data will all be nil values.
-Other devices running the same app branch, same wifi network are able to make the call with no issue. Then after some time, generally 1-2 days the problem phone will no longer have any trouble making the call and will continue on as before the issue started.
Throws error Code 303 (CFNetworkErrors.cfErrorHTTPParseFailure) in logs. Apple docs say it's a failure to parse the response from the server. I believe it's because the response data is null.
App Version:
This issue has shown up so far on iOS devices running 14.6 or higher.
Testing:
Used both an AlamoFire based and URLSession based network call and both can have the issue. The example code below is using the URLSession instead of the AlamoFire, but switching does not seem to have an effect on stopping devices from being able to develop the issue.
Changing from WiFi to Celluar internet has no effect, changing to another WiFi network has no effect either.
Deleting the App and reinstalling has no effect.
Because I have not figured out what triggers the issue I have only got my hands on a device with the issue a few times before it resolved itself and there was nothing to test.
I have managed to save some logs (print statements and some Firebase Analytics console messages). The segments I think are useful are pasted below.
Network call Code:
func makeNetworkCall(url: String, method: HTTPMethod = .get, parameters: Parameters? = nil, headers: HTTPHeaders? = nil, timeout: Double, completion: #escaping (DefaultURLRequestReturnModel) -> Void ) {
logger.debug("makingCall with: url= _\(url)_ method= _\(method)_, param= _\(parameters)_, headers= _\(headers)_")
var urlRequest: URLRequest?
var hasReturned: Bool = false
DispatchQueue.main.asyncAfter(deadline: .now() + timeout, execute: {
if !hasReturned {
completion(DefaultURLRequestReturnModel(isSuccess: false, statusCode: ErrorCodes.timeoutError.rawValue, action: .failure, dataResponse: nil))
}
})
do {
urlRequest = try URLRequest(url: url, method: method, headers: headers)
if let parameters = parameters {
urlRequest?.httpBody = try JSONSerialization.data(withJSONObject: parameters)
}
} catch {
completion(DefaultURLRequestReturnModel(isSuccess: false, statusCode: ErrorCodes.encodeError.rawValue, action: .failure, dataResponse: nil))
return
}
// Unwrap the optional urlRequest to confirm its != nil
guard var safeURLRequest = urlRequest else {
completion(DefaultURLRequestReturnModel(isSuccess: false, statusCode: ErrorCodes.encodeError.rawValue, action: .failure, dataResponse: nil))
return
}
if safeURLRequest.httpBody != nil {
safeURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
let session = URLSession.shared
logger.debug("before session.dataTask for url \(safeURLRequest.url)")
let task = session.dataTask(with: safeURLRequest, completionHandler: { data, response, error in
logger.debug("url session completion for safeURLRequest.url _\(safeURLRequest.url)_, response= _\(response)_, error= _\(error.debugDescription)_, data= _\(data)_")
if let httpResponse = response as? HTTPURLResponse {
logger.debug("url session completion for URL \(safeURLRequest.url): status \(httpResponse.statusCode)")
switch httpResponse.statusCode {
case 200, 204:
let defaultDataResponse = DefaultDataResponse(request: safeURLRequest, response: httpResponse, data: data, error: error)
completion(DefaultURLRequestReturnModel(isSuccess: true, statusCode: httpResponse.statusCode, action: httpResponse.statusCode == 200 ? .success : .successEmpty, dataResponse: defaultDataResponse))
default:
logger.debug("ON ERROR")
completion(DefaultURLRequestReturnModel(isSuccess: false, statusCode: httpResponse.statusCode, action: httpResponse.statusCode == 401 ? .authError : .failure, dataResponse: nil))
}
} else {
// This is Trigged in the error logs
logger.debug("url session completion for URL \(safeURLRequest.url): response = \(response) __ can't be cast to HTTPURLResponse")
if NetworkManager.isConnectedToInternet() { logger.networkNilEvent() }
completion(DefaultURLRequestReturnModel(isSuccess: false, statusCode: ErrorCodes.noResponseError.rawValue, action: .failure, dataResponse: nil))
}
hasReturned = true
})
task.resume()
}
Console Logs From A Problem Device:
debug: url session completion for safeURLRequest.url
Optional(https://cpht.auth0.com/oauth/ro), response= nil, error= _Optional(Error Domain=kCFErrorDomainCFNetwork Code=303 "(null)" UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask
.<9>,
_kCFStreamErrorDomainKey=4, NSErrorPeerAddressKey=<CFData 0x28375a080 [0x1f9151860]>{length = 16, capacity = 16, bytes =
0x100201bb6810b8f80000000000000000}, _kCFStreamErrorCodeKey=-2205,
NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask .<9>" )}), data= nil debug: url session completion for URL
Optional(https://cpht.auth0.com/oauth/ro): response = nil __ can't be
cast to HTTPURLResponse
Firebase Analytics Logs From A Problem Device:
I have replaced the IP Addresses from something like 100.0.0.0:443 to IP:443 in the following logs.
App name has been changed to MyAppName
2021-08-12 16:59:51.615734-0500 MyAppName[4586:1910198] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 1090aae88
2021-08-12 16:59:51.615828-0500 MyAppName[4586:1910198] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 1090aae88
2021-08-12 16:59:51.624933-0500 MyAppName[4586:1910198] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 1090aae88
2021-08-12 16:59:51.625051-0500 MyAppName[4586:1910198] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 1090aae88
2021-08-12 16:59:51.625570-0500 MyAppName[4586:1910198] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 1090aae88
2021-08-12 16:59:51.625716-0500 MyAppName[4586:1910198] [connection] nw_endpoint_handler_set_adaptive_read_handler [C14 IP:443 ready channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] unregister notification for read_timeout failed
2021-08-12 16:59:51.625773-0500 MyAppName[4586:1910198] [connection] nw_endpoint_handler_set_adaptive_write_handler [C14 IP:443 ready channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] unregister notification for write_timeout failed
2021-08-12 16:59:51.625828-0500 MyAppName[4586:1910198] [connection] nw_endpoint_handler_set_keepalive_handler [C14 IP:443 ready channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] unregister notification for keepalive failed
2021-08-12 16:59:51.626028-0500 MyAppName[4586:1910198] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 1090aae88
2021-08-12 16:59:51.626859-0500 MyAppName[4586:1910198] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 10909f7c8
2021-08-12 16:59:51.627061-0500 MyAppName[4586:1910198] [connection] nw_endpoint_handler_set_adaptive_read_handler [C13.2.1 IP:443 ready channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] unregister notification for read_timeout failed
2021-08-12 16:59:51.627118-0500 MyAppName[4586:1910198] [connection] nw_endpoint_handler_set_adaptive_write_handler [C13.2.1 IP:443 ready channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] unregister notification for write_timeout failed
2021-08-12 16:59:51.627257-0500 MyAppName[4586:1910198] [connection] nw_endpoint_handler_set_keepalive_handler [C13.2.1 IP:443 ready channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] unregister notification for keepalive failed
2021-08-12 16:59:51.641425-0500 MyAppName[4586:1909925] [] nw_protocol_instance_access_flow_state [C13.2.1:2] Failed to find flow 1090aae88
2021-08-12 16:59:51.647736-0500 MyAppName[4586:1909925] Task .<9> HTTP load failed, 529/0 bytes (error code: 303 [4:-2205])
2021-08-12 16:59:51.648181-0500 MyAppName[4586:1909923] Task .<9> finished with error [303] Error Domain=kCFErrorDomainCFNetwork Code=303 "(null)" UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<9>, _kCFStreamErrorDomainKey=4, NSErrorPeerAddressKey=<CFData 0x28375a080 [0x1f9151860]>{length = 16, capacity = 16, bytes = 0x100201bb6810b8f80000000000000000}, _kCFStreamErrorCodeKey=-2205, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask .<9>"
)}
2021-08-12 16:59:51.648326-0500 MyAppName[4586:1909925] [connection] nw_endpoint_handler_unregister_context [C13.2.1 IP:443 failed channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] Cannot unregister after flow table is released
2021-08-12 16:59:51.648393-0500 MyAppName[4586:1909925] [h3connection] 0x1099d1a18 13 closed with peer error 258
2021-08-12 16:59:51.648500-0500 MyAppName[4586:1909925] [connection] nw_endpoint_handler_add_write_request [C13.2.1 IP:443 failed channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] Cannot send after flow table is released
2021-08-12 16:59:51.648625-0500 MyAppName[4586:1909925] [connection] nw_write_request_report [C13] Send failed with error "Socket is not connected"
Thank you for any of your ideas on fixing this issue!
We had the same issuie that you described. In our case, one of our custom request headers exceeded the max header size limit of the webserver. Nginx has a max header size around 8kb and will return a 413 error to the client if you exceed this limit. for whatever reason, the ios app will not parse this response and throw a 303 error. After we increased the http2_max_header_size to 32kb, it worked.

Disable checking https certificate: Swift

I trying to make a https call to my web service from a ios application.
So I used:
//...
func sendMessage() {
let defaults = UserDefaults.standard
let url = URL(string: defaults.string(forKey:"host")! + ":" + defaults.string(forKey:"port")! + "/garage")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: String] = [
"identifier": defaults.string(forKey: "secret")!
]
request.httpBody = parameters.percentEncoded()
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
let responseString = String(data: data, encoding: .utf8)
debugPrint("responseString = \(responseString)")
}
task.resume()
}
//...
extension ViewController: URLSessionDelegate {
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//Trust the certificate even if not valid
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}
}
I installed the ca at on the target system too. But I also try to ignore the certificate.
I always get following error instead of a response:
2020-07-03 14:41:27.742361+0200 GarageOpener[5177:223905] ATS failed system trust
2020-07-03 14:41:27.742484+0200 GarageOpener[5177:223905] Connection 1: system TLS Trust evaluation failed(-9802)
2020-07-03 14:41:27.742642+0200 GarageOpener[5177:223905] Connection 1: TLS Trust encountered error 3:-9802
2020-07-03 14:41:27.742776+0200 GarageOpener[5177:223905] Connection 1: encountered error(3:-9802)
2020-07-03 14:41:27.746709+0200 GarageOpener[5177:223905] Task <63EC553D-485C-478D-813B-AF0C1D3D3223>.<1> HTTP load failed, 0/0 bytes (error code: -1200 [3:-9802])
2020-07-03 14:41:27.749778+0200 GarageOpener[5177:223905] Task <63EC553D-485C-478D-813B-AF0C1D3D3223>.<1> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x600002b187e0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
), NSUnderlyingError=0x600001773cf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x600002b187e0>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://subdomain.mydomain.de:443/garage, NSErrorFailingURLStringKey=https://subdomain.mydomain.de:443/garage, NSErrorClientCertificateStateKey=0}
"3"
error Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x600002b187e0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
), NSUnderlyingError=0x600001773cf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x600002b187e0>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://subdomain.mydomain.de:443/garage, NSErrorFailingURLStringKey=https://subdomain.mydomain.de:443/garage, NSErrorClientCertificateStateKey=0}
I know ignore isn't a good idea and it would allow man in the middle attacks. But at least the connection would be encrypted. And if somebody has the ability to make a man in the middle attack in my WLAN I have bigger problems than this.
Please help ;)
Okay, maybe it's time to answer my question.
The first I did wrong was the signing of the certificate.
I just set the domain/ip-address of the server in the Common Name (CN) entry of the certificate.
That is an outdated solution. You need to set the subjectAltName for modern applications: http://wiki.cacert.org/FAQ/subjectAltName .
But it feels very ugly to use the instructions from that wiki site to self-sign a certificate. So I used the awesome tool certstrap: https://github.com/square/certstrap
After that:
I passed the server.key and server.crt (private and signed public
key) to the server and configured everything fine.
I downloaded the CA (ca.crt) that I created (on the iphone).
You need to go to the settings->general->profiles and trust your
certificate.
Finally, you need to trust the certificate again:
https://support.apple.com/en-us/HT204477#:~:text=If%20you%20want%20to%20turn,Mobile%20Device%20Management%20(MDM).
Done. My application worked!

Django Rest Framework: Error when handle file upload by iOS Swift Client

I have an issue when handling file upload by iOS Swift Client. I describe it totally below
My model:
def avatar_photo_upload(instance, filename):
if filename:
ext = filename.split('.')[-1]
filename = 'avatar.%s' % (ext)
else:
filename = 'avatar.jpg'
return "avatar/%s/%s" %('profile', filename)
class Profile(models.Model):
avatar = models.FileField("Uploaded avatar of profile", storage=OverwriteStorage(), upload_to=avatar_photo_upload, null=True, blank=True)
My serializer:
class PhotoUpdateSerializer(ModelSerializer):
file = ImageField(max_length=100000, allow_empty_file=False, use_url=False)
class Meta:
model = Profile
fields = [
'file',
]
My view:
class UploadPhotoAPIView(ModelViewSet):
serializer_class = PhotoUpdateSerializer
queryset = Profile.objects.all()
parser_classes = (JSONParser, MultiPartParser, FormParser,)
permission_classes = (IsAuthenticated,)
def upload_avatar(self, request):
serializer = self.get_serializer(data=request.data, context={"request": request})
logger.info('Information incoming!')
if serializer.is_valid():
profile = Profile.objects.get(user=request.user)
profile.avatar = request.FILES.get('file')
profile.save()
return Response({ 'status': 'ok', 'avatar': get_avatar_url(request, '300x300', 'user', profile.user_id) }, status=status.HTTP_201_CREATED)
else:
logger.error('Toan Error' + str(serializer.errors))
return Response(serializer.errors, status=status.HTTP_501_NOT_IMPLEMENTED)
Finally, this is my url:
url(r'^account/upload_avatar/$', UploadPhotoAPIView.as_view({'post': 'upload_avatar'}))
I believed that I make it all the right way until test API in iOS Swift, it return error:
Request by client:
func uploadImage(image:UIImage) {
let imageData:NSData = UIImageJPEGRepresentation(image, 100)
SRWebClient.POST("https://api.com/api/v1/users/account/upload_avatar/")
.data(imageData, fieldName:"file", data: ["filename":"avatar","ext":".jpg"])
.send({(response:AnyObject!, status:Int) -> Void in
// process success response
},failure:{(error:NSError!) -> Void in
// process failure response
})
}
Error traceback:
[Request]: POST
https://api.com/api/v1/users/account/upload_avatar/
[Response]: { URL:
https://api.com/api/v1/users/account/upload_avatar/ } {
Status Code: 501, Headers {
"Content-Length" = (
84
);
"Content-Type" = (
"application/json"
);
Date = (
"Wed, 10 Oct 2018 10:41:31 GMT"
);
Server = (
cloudflare
);
Vary = (
Origin
);
allow = (
"POST, OPTIONS"
);
"cf-ray" = (
"46787998dfaa8502-HKG"
);
"expect-ct" = (
"max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
);
"x-frame-options" = (
SAMEORIGIN
); } } [Data]: 84 bytes [Result]: SUCCESS: {
file = (
"The submitted data was not a file. Check the encoding type on the form."
); } [Timeline]: Timeline: { "Request Start Time": 560860890.985, "Initial Response Time": 560860891.099, "Request Completed Time":
560860891.100, "Serialization Completed Time": 560860891.100, "Latency": 0.114 secs, "Request Duration": 0.115 secs, "Serialization
Duration": 0.000 secs, "Total Duration": 0.115 secs } ▿ request :
Optional
▿ some : https://api.com/api/v1/users/account/upload_avatar/
▿ url : Optional
▿ some : https://api.com/api/v1/users/account/upload_avatar/
- _url : https://api.com/api/v1/users/account/upload_avatar/
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __C.NSURLRequestNetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional
- some : "POST"
▿ allHTTPHeaderFields : Optional>
▿ some : 2 elements
▿ 0 : 2 elements
- key : "Content-Type"
- value : "application/x-www-form-urlencoded; charset=utf-8"
▿ 1 : 2 elements
- key : "Authorization"
- value : "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyMSwidXNlcm5hbWUiOiJkdW9uZ251aGFiYW5nIiwiZXhwIjoyNDAzMTY4MDU5LCJlbWFpbCI6ImRyYWZ0bGlnb25ncXVhbjdAZ21haWwuY29tIn0.ZfDBOaAhKsRSpZl3mP87doR34UtlGISfeqJYlJnxcVI"
▿ httpBody : Optional
▿ some : 105 bytes
- count : 105
▿ pointer : 0x00006000025d2510
- pointerValue : 105553155925264
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false ▿ response : Optional
- some : { URL: https://api.com/api/v1/users/account/upload_avatar/ } {
Status Code: 501, Headers {
"Content-Length" = (
84
);
"Content-Type" = (
"application/json"
);
Date = (
"Wed, 10 Oct 2018 10:41:31 GMT"
);
Server = (
cloudflare
);
Vary = (
Origin
);
allow = (
"POST, OPTIONS"
);
"cf-ray" = (
"46787998dfaa8502-HKG"
);
"expect-ct" = (
"max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
);
"x-frame-options" = (
SAMEORIGIN
); } } ▿ data : Optional
▿ some : 84 bytes
- count : 84
▿ pointer : 0x00006000025d0c00
- pointerValue : 105553155918848 ▿ result : SUCCESS: {
file = (
"The submitted data was not a file. Check the encoding type on the form."
); }
▿ success : 1 element
▿ 0 : 2 elements
- key : file
▿ value : 1 element
- 0 : The submitted data was not a file. Check the encoding type on the form. ▿ timeline : Timeline: { "Request Start Time":
560860890.985, "Initial Response Time": 560860891.099, "Request Completed Time": 560860891.100, "Serialization Completed Time":
560860891.100, "Latency": 0.114 secs, "Request Duration": 0.115 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.115 secs }
- requestStartTime : 560860890.984645
- initialResponseTime : 560860891.099072
- requestCompletedTime : 560860891.099792
- serializationCompletedTime : 560860891.099964
- latency : 0.11442697048187256
- requestDuration : 0.11514699459075928
- serializationDuration : 0.00017201900482177734
- totalDuration : 0.11531901359558105 ▿ _metrics : Optional
- some : (Task Interval) <_NSConcreteDateInterval: 0x600000b68980> (Start Date) 2018-10-10 10:41:30 +0000 + (Duration) 0.115085 seconds =
(End Date) 2018-10-10 10:41:31 +0000 (Redirect Count) 0 (Transaction
Metrics) (Request) { URL:
https://api.com/api/v1/users/account/upload_avatar/ }
(Response) { URL:
https://api.com/api/v1/users/account/upload_avatar/ } {
Status Code: 501, Headers {
"Content-Length" = (
84
);
"Content-Type" = (
"application/json"
);
Date = (
"Wed, 10 Oct 2018 10:41:31 GMT"
);
Server = (
cloudflare
);
Vary = (
Origin
);
allow = (
"POST, OPTIONS"
);
"cf-ray" = (
"46787998dfaa8502-HKG"
);
"expect-ct" = (
"max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
);
"x-frame-options" = (
SAMEORIGIN
); } } (Fetch Start) 2018-10-10 10:41:30 +0000 (Domain Lookup Start) (null) (Domain Lookup End) (null) (Connect Start) (null)
(Secure Connection Start) (null) (Secure Connection End) (null)
(Connect End) (null) (Request Start) 2018-10-10 10:41:30 +0000
(Request End) 2018-10-10 10:41:30 +0000 (Response Start) 2018-10-10
10:41:31 +0000 (Response End) 2018-10-10 10:41:31 +0000 (Protocol
Name) h2 (Proxy Connection) NO (Reused Connection) YES (Fetch Type)
Network Load
What is the issue and it come from server or client? Please give me a advice. Thank in advance!
you have to pass the content type as a multipart form data.
class UploadPhotoAPIView(ModelViewSet):
serializer_class = PhotoUpdateSerializer
queryset = Profile.objects.all()
parser_classes = (JSONParser, MultiPartParser, FormParser,)
permission_classes = (IsAuthenticated,)
def upload_avatar(self, request):
serializer = self.get_serializer(instance=Profile.objects.get(user=request.user), data=request.data, context={"request": request})
logger.info('Information incoming!')
if serializer.is_valid():
serializer.save()
return Response({ 'status': 'ok', 'avatar': get_avatar_url(request, '300x300', 'user', profile.user_id) }, status=status.HTTP_201_CREATED)
else:
logger.error('Toan Error' + str(serializer.errors))
return Response(serializer.errors, status=status.HTTP_501_NOT_IMPLEMENTED)
in client side send data in multipart form data

How to connect to Socket.IO swift?

I am having trouble connecting to Socket.IO chat..
import UIKit
import SocketIO
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let manager = SocketManager(socketURL: URL(string: "wss://socket-io-chat.now.sh/socket.io/")!, config: [.log(true), .compress])
let socket = manager.defaultSocket
socket.on(clientEvent: .connect) {data, ack in
print("socket connected")
}
socket.on("new message") {data, ack in
print("new Messages")
}
socket.connect()
}
}
I am using the latest socket.io library and already added app transport in info.plist.
here's what the logs says..
2018-01-22 16:56:46.316676+0800 ExampleSocket[6963:2231315] LOG SocketEngine: Got message: 40
2018-01-22 16:56:46.317249+0800 ExampleSocket[6963:2231315] LOG SocketEngine: Writing poll: has data: false
2018-01-22 16:56:46.317771+0800 ExampleSocket[6963:2231315] LOG SocketEnginePolling: Sending poll: as type: 2
2018-01-22 16:56:46.323959+0800 ExampleSocket[6963:2231318] TIC Read Status [2:0x0]: 1:57
2018-01-22 16:56:46.324082+0800 ExampleSocket[6963:2231318] TIC Read Status [2:0x0]: 1:57
2018-01-22 16:56:46.330099+0800 ExampleSocket[6963:2231315] LOG SocketEnginePolling: Created POST string: 1:2
2018-01-22 16:56:46.330615+0800 ExampleSocket[6963:2231315] LOG SocketEnginePolling: POSTing
2018-01-22 16:56:46.330744+0800 ExampleSocket[6963:2231315] LOG SocketEngine: Engine is being released
try the below code:
var socketClient: SocketIOClient!
if let url = URL(string: "wss://socket-io-chat.now.sh/socket.io/") {
let socketClient = SocketIOClient(socketURL: url, config: [.log(true),.forcePolling(true)])
socketClient.connect()
}
socketClient.onAny { (socEvent) in
if let status = socEvent.items as? [SocketIO.SocketIOClientStatus] {
if let first = status.first {
switch first {
case .connected:
print("Socket: connected")
break
case .disconnected:
print("Socket: disconnected")
break
case .notConnected:
print("Socket: notConnected")
break
case .connecting:
print("Socket: connecting")
break
}
}
}
}

Fatal error using AlamoFireImage to load a url of Arrays using the .af_setImage method in a CollectionView

I'm getting an Array of urls from my REST API and I want to use them to load images from the server using AlamofireImage .af_setImage method for my collection view cells. But I'm getting the following error message in the debug console:
fatal error: unexpectedly found nil while unwrapping an Optional value
This is the code I'm using:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCellIdentifiers.searchResultCell, for: indexPath) as! CreaTuCanastaCollectionViewCell
let urlString = productPictures[indexPath.item]
if let url = URL(string: productPictures[indexPath.item]) {
cell.imageView.af_setImage(withURL: url)
}
return cell
}
}
The strange thing is that the debug console throws this:
Which means the values are there, yet it keeps throwing me the
fatal error:
unexpectedly found nil while unwrapping an Optional value
Any ideas?
Edit
I tried using SDImage instead of AlamoFireImage
if let url = URL(string: productPictures[indexPath.item]) {
cell.imageView.sd_setImage(with: url)
}
And I get the same results
Edit
I tried a different approach this time I put this code inside the cellForItemAt method:
Alamofire.request(urlArray).responseImage { response in
debugPrint(response)
print(response.request)
print(response.response)
print(response.result)
if let image = response.result.value {
cell.imageView.image = image
}
Which gives me this response in the debugging console:
SUCCESS
<UIImage: 0x620000283fc0>, {300, 300}
[Response]: <NSHTTPURLResponse: 0x62800002cb80> { URL: https://i1.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg?fit=600%2C600&ssl=1 } { status code: 200, headers {
"Cache-Control" = "public, max-age=63115200";
"Content-Length" = 24757;
"Content-Type" = "image/jpeg";
Date = "Thu, 01 Dec 2016 06:06:41 GMT";
Etag = "\"629f656831de2958\"";
Expires = "Sat, 01 Dec 2018 18:00:39 GMT";
"Last-Modified" = "Thu, 01 Dec 2016 06:00:39 GMT";
Link = "<https://pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg>; rel=\"canonical\"";
Server = nginx;
Vary = Accept;
"x-bytes-saved" = 2467;
"x-content-type-options" = nosniff;
"x-nc" = "HIT bur 66";
} }
[Data]: 24757 bytes
[Result]: SUCCESS: <UIImage: 0x6280002830c0>, {300, 300}
[Timeline]: Timeline: { "Request Start Time": 502265200.175, "Initial Response Time": 502265200.756, "Request Completed Time": 502265200.813, "Serialization Completed Time": 502265200.821, "Latency": 0.581 secs, "Request Duration": 0.638 secs, "Serialization Duration": 0.008 secs, "Total Duration": 0.645 secs }
Optional(https://i1.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg?fit=600%2C600&ssl=1)
Optional(<NSHTTPURLResponse: 0x62800002cb80> { URL: https://i1.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg?fit=600%2C600&ssl=1 } { status code: 200, headers {
"Cache-Control" = "public, max-age=63115200";
"Content-Length" = 24757;
"Content-Type" = "image/jpeg";
Date = "Thu, 01 Dec 2016 06:06:41 GMT";
Etag = "\"629f656831de2958\"";
Expires = "Sat, 01 Dec 2018 18:00:39 GMT";
"Last-Modified" = "Thu, 01 Dec 2016 06:00:39 GMT";
Link = "<https://pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg>; rel=\"canonical\"";
Server = nginx;
Vary = Accept;
"x-bytes-saved" = 2467;
"x-content-type-options" = nosniff;
"x-nc" = "HIT bur 66";
} })
SUCCESS
<UIImage: 0x6280002830c0>, {300, 300}
2016-12-01 00:06:41.110589 pixan[9961:2940658] []
But I'm still getting the same mistake.
var urlstr = ""
if let urlString = productPictures[indexPath.item] as? String
{
urlstr = urlString
}
cell.imageView.sd_setImageWithURL(NSURL(string: urlstr!), placeholderImage: UIImage(named: "imgPlaceHolder"), completed: { (image, error, cacheType, imageURL) -> Void in})